<template>
    <div class="hc-page-box">
        <HcCard>
            <template #header>
                <HcTooltip keys="tentative_material_approach_add">
                    <el-button type="primary" hc-btn @click="addFormModalClick">
                        <HcIcon name="add-circle"/>
                        <span>新增</span>
                    </el-button>
                </HcTooltip>
                <HcTooltip keys="tentative_material_approach_edit">
                    <el-button hc-btn :disabled="tableCheckedKeys.length <= 0" @click="editFormModalClick">
                        <HcIcon name="edit"/>
                        <span>编辑</span>
                    </el-button>
                </HcTooltip>
                <HcTooltip keys="tentative_material_approach_copy">
                    <el-button hc-btn :disabled="tableCheckedKeys.length <= 0" @click="copyTableModalClick">
                        <HcIcon name="file-copy-2"/>
                        <span>复制</span>
                    </el-button>
                </HcTooltip>
                <HcTooltip keys="tentative_material_approach_del">
                    <el-button hc-btn :disabled="tableCheckedKeys.length <= 0" @click="delModalClick">
                        <HcIcon name="delete-bin-2"/>
                        <span>删除</span>
                    </el-button>
                </HcTooltip>
                <HcTooltip keys="tentative_material_approach_printer">
                    <el-button hc-btn :disabled="tableCheckedKeys.length <= 0" :loading="printerLoading" @click="printerClick">
                        <HcIcon name="printer"/>
                        <span>打印</span>
                    </el-button>
                </HcTooltip>
                <HcTooltip keys="tentative_material_approach_import">
                    <el-button hc-btn @click="importModalClick">
                        <HcIcon name="folder-upload"/>
                        <span>导入</span>
                    </el-button>
                </HcTooltip>
            </template>
            <template #search>
                <div class="w-40">
                    <el-select v-model="searchForm.materialType" placeholder="请选择材料类型" clearable>
                        <el-option v-for="item in typeData" :key="item.value" :label="item['dictValue']" :value="item['dictKey']"/>
                    </el-select>
                </div>
                <div class="w-64 ml-2">
                    <HcDatePicker :dates="betweenTime" clearable @change="betweenTimeUpdate"/>
                </div>
                <div class="w-72 ml-2">
                    <el-input v-model="searchForm.queryValue" placeholder="请输入名称、规格、材料编号进行查询" clearable @keyup="keyUpEvent"/>
                </div>
                <div class="ml-2">
                    <el-button type="primary" @click="searchClick">
                        <HcIcon name="search-2"/>
                        <span>搜索</span>
                    </el-button>
                </div>
            </template>
            <HcTable ref="tableRef" :column="tableColumn" :datas="tableData" :loading="tableLoading" isCheck @selection-change="tableSelection">
                <template #materialType="{row}">{{getRowTableMaterialType(row['materialType'])}}</template>
                <template #materialCount="{row}">{{row.materialCount===-1?"":row.materialCount}}</template>
                <template #materialPrice="{row}">{{row.materialPrice===-1?"":row.materialPrice}}</template>
                <template #action="{row}">
                    <HcTooltip keys="tentative_material_approach_annex">
                        <el-button type="primary" size="small" plain @click="viewAttachmentModalClick(row)">附件</el-button>
                    </HcTooltip>
                    <HcTooltip keys="tentative_material_approach_sampling">
                        <el-button type="primary" size="small" plain @click="samplingRecordModalClick(row)">取样记录</el-button>
                    </HcTooltip>
                </template>
            </HcTable>
            <template #action>
                <HcPages :pages="searchForm" @change="pageChange"/>
            </template>
        </HcCard>

        <!--新增/编辑-->
        <HcDialog :show="addEditFormModal" :title="`${addEditFormModel.id?'编辑':'新增'}材料进场`" widths="45rem" :loading="addEditFormLoading" @close="addEditFormModalClose" @save="addEditFormClick">
            <el-form ref="addEditFormRef" :model="addEditFormModel" :rules="addEditFormRules" label-width="auto" size="large">
                <div class="hc-form-item">
                    <el-form-item label="材料类型" prop="materialType">
                        <el-select v-model="addEditFormModel.materialType" block>
                            <el-option v-for="item in typeData" :label="item['dictValue']" :value="item['dictKey']"/>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="材料单价">
                        <el-input v-model="addEditFormModel.materialPrice"/>
                    </el-form-item>
                </div>
                <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-input v-model="addEditFormModel.materialCount"    onkeyup="value = value.replace(/^\D*(\d*(?:\.\d{0,2})?).*$/g,'$1')"/>
                    </el-form-item>
                </div>
                <div class="hc-form-item">
                    <el-form-item label="规格型号" prop="specificationModel">
                        <el-input v-model="addEditFormModel.specificationModel"/>
                    </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="材料编号" prop="materialNumber">
                        <el-input v-model="addEditFormModel.materialNumber"/>
                    </el-form-item>
                    <el-form-item label="生产批号">
                        <el-input v-model="addEditFormModel.batchNumber"/>
                    </el-form-item>
                </div>
                <div class="hc-form-item">
                    <el-form-item label="进场日期">
                        <el-date-picker type="date" v-model="addEditFormModel.mobilizationDate" class="block" value-format="YYYY-MM-DD" :clearable="false"/>
                    </el-form-item>
                    <el-form-item label="拟用部位">
                        <el-input v-model="addEditFormModel.proposedPosition"/>
                    </el-form-item>
                </div>
                <div class="hc-form-item">
                    <el-form-item label="供应商单位">
                        <el-input v-model="addEditFormModel.supplierUnit"/>
                    </el-form-item>
                    <el-form-item label="生产地/厂家">
                        <el-input v-model="addEditFormModel.placeOfProduction"/>
                    </el-form-item>
                </div>
                <el-form-item label="生产合格证">
                    <FormItemUpload v-model="addEditFormModel.productionCertificate"/>
                </el-form-item>
                <el-form-item label="厂家质检报告">
                    <FormItemUpload v-model="addEditFormModel.qualityInspectionReport"/>
                </el-form-item>
                <el-form-item label="其他附件">
                    <FormItemUpload v-model="addEditFormModel.otherAccessories"/>
                </el-form-item>
            </el-form>
        </HcDialog>

        <!--复制材料登记信息-->
        <HcDialog :show="copyTableModal" title="复制材料登记信息" widths="60rem" isTable :loading="copyTableLoading" @close="copyTableModalClose" @save="copyTableClick">
            <HcTable :column="copyTableColumn" :datas="copyTableData">
                <template #materialNumber="{row}">
                    <el-input v-model="row.materialNumber" :class="row.isMaterialNumber?'is-error':''" placeholder="请输入材料编号" @blur="materialNumberBlur(row)"/>
                </template>
                <template #action="{index}">
                    <el-button type="danger" size="small" plain @click="materialNumberDel(index)">删除</el-button>
                </template>
            </HcTable>
        </HcDialog>

        <!--导入-->
        <HcDialog :show="importModal" title="导入" widths="38rem" isRowFooter @close="importModalClose">
            <HcDragUpload ref="uploadRef" action="mobilization/import" :datas="uploadData" @progress="uploadprogress" @finished="uploadFinished"/>
            <template #leftRowFooter>
                <el-button size="large" @click="downloadImportClick">
                    <HcIcon name="download-2"/>
                    <span>下载模板</span>
                </el-button>
            </template>
            <template #rightRowFooter>
                <el-button size="large" @click="importModalClose">
                    <HcIcon name="close"/>
                    <span>取消导入</span>
                </el-button>
                <el-button type="primary" hc-btn :loading="importModalLoading" @click="importModalYesClick">
                    <HcIcon name="folder-upload"/>
                    <span>确认导入</span>
                </el-button>
            </template>
        </HcDialog>

        <!--查看附件-->
        <HcDialog :show="viewAttachmentModal" title="查看附件" widths="70rem" :footer="false" isTable @close="viewAttachmentModalClose">
            <template #extra>
                <HcNewSwitch :datas="tabTypeTab" :keys="tabTypeKey" @change="tabTypeChange" :disabled="tableRowPdfDisabled"/>
            </template>
            <div class="hc-switch-tab-content">
                <div class="h-full w-full">
                    <iframe allow="display-capture" width='100%' height='100%' frameborder='1' :src="tableRowData[tabTypeKey]" v-if="tableRowData[tabTypeKey]"/>
                    <div class="hc-no-table-form" v-else>
                        <div class="table-form-no">
                            <img :src="notableform" alt=""/>
                            <div class="desc">暂无 PDF 数据，请上传</div>
                            <HcDragUpload autoUpload @progress="tableRowPdfProgress" @finished="tableRowPdfFinished"/>
                        </div>
                    </div>
                </div>
            </div>
        </HcDialog>

        <!--取样记录-->
        <HcDialog :show="samplingRecordModal" title="取样记录" widths="60%" :footer="false" isTable @close="samplingRecordModalClose">
            <HcTable :column="samplingTableColumn" :datas="samplingTableData" :loading="samplingTableLoading" :isIndex="false">
                <template #isOutsourcing="{row}">
                    <span>{{row.isOutsourcing === 1 ? '是':'否'}}</span>
                </template>
            </HcTable>
        </HcDialog>

    </div>
</template>

<script setup>
import {ref, onMounted} from "vue";
import {useAppStore} from "~src/store";
import HcDragUpload from "./components/HcDragUpload.vue"
import FormItemUpload from "./components/FormItemUpload.vue"
import notableform from '~src/assets/view/notableform.svg';
import approachApi from "~api/tentative/material/approach"
import {formValidate, getArrValue, getIndex, deepClone} from "vue-utils-plus"
import {getDictionary} from "~api/other";

//初始变量
const useAppState = useAppStore()

//全局变量
const projectId = ref(useAppState.getProjectId);
const contractId = ref(useAppState.getContractId);

//渲染完成
onMounted(() => {
    getMaterialType()
    getTableData()
})

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

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

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

//日期时间被选择
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:'materialNumber', name: '材料编号'},
    {key:'mobilizationDate', name: '进场日期'},
    {key:'materialName', name: '材料名称'},
    {key:'materialType', name: '材料类型'},
    {key:'specificationModel', name: '规格型号'},
    {key:'supplierUnit', name: '供应商单位'},
    {key:'materialPrice', name: '材料单价'},
    {key:'materialCount', name: '材料数量'},
    {key:'calculationUnit', name: '计算单位'},
    {key:'batchNumber', name: '生产批号'},
    {key:'placeOfProduction', name: '生产地/厂家'},
    {key:'proposedPosition', name: '拟用部位'},
    {key:'userName', name: '记录人'},
    {key:'action', name: '操作', width: 150, fixed: 'right', align: 'center'},
])
const tableRowData = ref({})

//获取数据
const tableLoading = ref(false)
const tableData = ref([])
const getTableData = async () => {
    tableLoading.value = true
    const { error, code, data } = await approachApi.queryPage({
        projectId: projectId.value,
        contractId: contractId.value,
        ...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.filter((item) => {
        return (item??'') !== '';
    })
}

//新增 材料进场
const addEditFormModal = ref(false)
const addFormModalClick = () => {
    addEditFormModel.value = {}
    addEditFormModal.value = true
}
//编辑 材料进场
const editFormModalClick = () => {
    const keys = tableCheckedKeys.value
    if (keys.length === 1) {
        addEditFormModel.value = keys[0]
        addEditFormModel.value.materialType= addEditFormModel.value.materialType+''
        addEditFormModel.value.materialCount=addEditFormModel.value.materialCount===-1?'':addEditFormModel.value.materialCount
        addEditFormModel.value.materialPrice=addEditFormModel.value.materialPrice===-1?'':addEditFormModel.value.materialPrice
        addEditFormModal.value = true
    } else if (keys.length > 1) {
        window?.$message?.warning('只能选择一条数据编辑')
    }
}
const addEditFormModalClose = () => {
    addEditFormModal.value = false
    addEditFormModel.value = {}
}

//新增/编辑 表单
const addEditFormRef = ref(null)
const addEditFormModel = ref({})
const addEditFormRules = {
    materialType: {
        required: true,
        trigger: 'change',
        message: "请选择材料类型"
    },
    materialName: {
        required: true,
        trigger: 'blur',
        message: "请输入材料名称"
    },
    specificationModel: {
        required: true,
        trigger: 'blur',
        message: "请输入规格型号"
    },
    materialNumber: {
        required: true,
        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 approachApi.verification({
        projectId: projectId.value,
        contractId: contractId.value,
        materialNumber: val,
        id: addEditFormModel.value.id ?? ''
    })
    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 } = await approachApi.submitForm({
            ...addEditFormModel.value,
            projectId: projectId.value,
            contractId: contractId.value
        })
        //处理数据
      
        if (!error && code === 200) {
            window?.$message?.success('操作成功')
            addEditFormModal.value = false
            setTimeout(() => {
                addEditFormLoading.value = false
            }, 1000);
            await getTableData()
        }
    }
}

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

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

//效验材料编号
const materialNumberBlur = async (row) => {
    const number = row?.materialNumber ?? ''
    if (number) {
        const ver = await verification(number)
        row.isMaterialNumber = !ver
    } else {
        row.isMaterialNumber = true
    }
}

//删除
const materialNumberDel = (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 = () => {
    const rows = copyTableData.value
    if (rows.length > 0) {
        //判断是否满足条件
        const result = rows.every(({isMaterialNumber})=> {
            return isMaterialNumber === false
        })
        //判断状态
        if (result) {
            for (let i = 0; i < rows.length; i++) {
                rows[i].dataNumber = i
            }
            tableCopyData(rows)
        } else {
            window.$message?.warning('请先完善材料编号')
        }
    } else {
        window.$message?.warning('请先在列表勾选要复制的数据')
        copyTableModal.value = false
    }
}

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

//删除
const delModalClick = () => {
    window?.$messageBox?.alert('请谨慎考虑后，确认是否需要删除？', '删除提醒', {
        showCancelButton: true,
        confirmButtonText: '确认删除',
        cancelButtonText: '取消',
        type: 'warning',
        callback: (action) => {
            if (action === 'confirm') {
                tableRemoveData()
            }
        }
    })
}

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

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

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

//导入弹窗
const importModal = ref(false)
const importModalClick = () => {
    importModal.value = true
    uploadData.value = {
        contractId: contractId.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
}


//查看附件
const viewAttachmentModal = ref(false)
const viewAttachmentModalClick = (row) => {
    tableRowData.value = row
    viewAttachmentModal.value = true
}

//类型tab数据和相关处理
const tabTypeKey = ref('productionCertificate')
const tabTypeTab = ref([
    {key:'productionCertificate',  name: '生产合格证'},
    {key:'qualityInspectionReport', name: '厂家质检报告'},
    {key:'otherAccessories', name: '其他文件'},
]);
const tabTypeChange = (item) => {
    tabTypeKey.value = item?.key
}

//上传进度
const tableRowPdfDisabled = ref(false)
const tableRowPdfProgress = (res) => {
    tableRowPdfDisabled.value = res
}

//上传完成
const tableRowPdfFinished = async (data) => {
    tableRowPdfDisabled.value = true
    const row = tableRowData.value, key = tabTypeKey.value
    row[key] = data?.pdfUrl
    //保存请求
    const { error, code } = await approachApi.submitForm({
        ...row,
        projectId: projectId.value,
        contractId: contractId.value
    })
    //处理数据
    tableRowData.value = row
    tableRowPdfDisabled.value = false
    if (!error && code === 200) {
        window?.$message?.success('操作成功')
        await getTableData()
    }
}

//关闭查看附件
const viewAttachmentModalClose = () => {
    viewAttachmentModal.value = false
}


//取样记录
const samplingRecordModal = ref(false)
const samplingRecordModalClick = async (row) => {
    samplingRecordModal.value = true
    samplingTableLoading.value = true
    const { data } = await approachApi.samplingRecord({
        projectId: projectId.value,
        contractId: contractId.value,
        id: row.id,
    })
    samplingTableLoading.value = false
    samplingTableData.value = getArrValue(data)
}

//取样记录数据
const samplingTableColumn = ref([
    {key:'specificationNumber', name: '样品编号'},
    {key:'materialName', name: '样品名称'},
    {key:'samplingDate', name: '取样日期'},
    {key:'userName', name: '取样人'},
    {key:'materialCount', name: '试样数量'},
    {key:'isOutsourcing', name: '是否外委'},
])
const samplingTableData = ref([])
const samplingTableLoading = ref(false)

//关闭取样记录
const samplingRecordModalClose = () => {
    samplingRecordModal.value = false
}

//下载导入模板
const downloadImportClick = () => {
    window.open('https://bladex-test-info.oss-cn-chengdu.aliyuncs.com//upload/20221109/fea12aaee9d964d2d9f894cc6bf4a2f6.xlsx','_blank')
}

//拼接ID
const rowsToId = (rows) => {
    return rows.map((obj) => {
        return obj.id;
    }).join(",")
}
</script>

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