<!--  -->
<template>
    <div class="hc-layout-box">
        <HcNewCard>
            <template #header>
                <HcTooltip keys="gauge-testdata-add">
                    <el-button hc-btn type="primary" @click="AddRowClick">
                        <HcIcon name="add-box" />
                        <span>新增</span>
                    </el-button>
                </HcTooltip>
                <HcTooltip keys="gauge-testdata-import">
                    <el-button hc-btn @click="importModalClick">
                        <HcIcon name="upload-cloud" />
                        <span>导入</span>
                    </el-button>
                </HcTooltip>
                <div class="w-60 ml-6">
                    <el-input v-model="searchForm.searchValue" clearable :placeholder="placeTitle" @keyup="keyUpEvent" />
                </div>
                <div class="ml-2">
                    <el-button type="primary" @click="searchClick">
                        <HcIcon name="search-2" />
                        <span>搜索</span>
                    </el-button>
                </div>
            </template>
            <template #extra>
                <HcNewSwitch :datas="tabsTypeData" :keys="tabsTypeKey" size="default" @change="tabsTypeChange" />
            </template>
            <HcTable v-if="tabsTypeKey === '0'" :column="tableColumn" :datas="tableData" :laoding="tableLoading" is-new :index-style="{ width: 60 }">
                <template #action="{ row }">
                    <HcTooltip keys="gauge-station-edit">
                        <el-button size="small" text type="primary" @click="handleLevelEdit(row)">编辑</el-button>
                    </HcTooltip>
                    <HcTooltip keys="gauge-station-del">
                        <el-button v-del-com:[handleLevelDelete]="row" size="small" text type="danger">删除</el-button>
                    </HcTooltip>
                </template>
            </HcTable>
            <HcTable v-if="tabsTypeKey === '1'" :column="matchTableColumn" :datas="matchData" :laoding="matchtableLoading" is-new :index-style="{ width: 60 }">
                <template #action="{ row }">
                    <HcTooltip keys="gauge-testdata-edit">
                        <el-button size="small" text type="primary" @click="handmatchEdit(row)">编辑</el-button>
                    </HcTooltip>
                    <HcTooltip keys="gauge-testdata-del">
                        <el-button v-del-com:[handmathDelete]="row" size="small" text type="danger">删除</el-button>
                    </HcTooltip>
                </template>
            </HcTable>
            <template #action>
                <HcPages :pages="searchForm" @change="pageChange" />
            </template>

            <!-- 新增/编辑 弹框 -->
            <hc-new-dialog
                v-model="testModal"
                :title="`${formRowValue?.id || matchformRowValue?.id ? '编辑' : '新增'}${tabsTypeKey === '0' ? '原材' : '配合比'}`"
                widths="47rem"
                :is-table="tabsTypeKey === '1'"
                @close="testModalClose"
            >
                <el-form v-if="tabsTypeKey === '0'" ref="formRowRef" :model="formRowValue" :rules="rulesRow" label-width="auto" size="large">
                    <el-form-item label="材料名称" prop="name">
                        <el-input v-model="formRowValue.name" placeholder="请输入材料名称" />
                    </el-form-item>
                    <el-form-item label="规格型号" prop="specification">
                        <el-input v-model="formRowValue.specification" placeholder="请输入规格型号" />
                    </el-form-item>
                    <el-form-item label="生产厂商" prop="manufacturers">
                        <el-input v-model="formRowValue.manufacturers" placeholder="请输入生产厂商" />
                    </el-form-item>
                    <el-form-item label="存放地点或料厂号" prop="storageSite">
                        <el-input v-model="formRowValue.storageSite" placeholder="请输入存放地点或料厂号" />
                    </el-form-item>
                    <el-form-item label="试验批准文号" prop="batchNumber">
                        <el-input v-model="formRowValue.batchNumber" placeholder="请输入试验批准文号" />
                    </el-form-item>
                    <el-form-item label="准备数量" prop="total">
                        <el-input v-model="formRowValue.total" placeholder="请输入准备数量" />
                    </el-form-item>
                </el-form>
                <el-form v-if="tabsTypeKey === '1'" ref="matchformRowRef" :model="matchformRowValue" :rules="matchrulesRow" label-width="auto" size="large">
                    <el-form-item label="配合比报告编号" prop="name">
                        <el-input v-model="matchformRowValue.reportNumber" placeholder="请输入" />
                    </el-form-item>
                    <el-form-item label="设计强度" prop="designStrength">
                        <el-input v-model="matchformRowValue.designStrength" placeholder="请输入" />
                    </el-form-item>
                    <el-form-item label="水胶比" prop="waterBinderRatio">
                        <el-input v-model="matchformRowValue.waterBinderRatio" placeholder="请输入" />
                    </el-form-item>
                    <el-form-item label="水泥" prop="cement">
                        <el-input
                            v-model="matchformRowValue.cement" placeholder="请输入"
                        />
                    </el-form-item>
                    <el-form-item label="砂" prop="total">
                        <el-input
                            v-model="matchformRowValue.sand" placeholder="请输入"
                        />
                    </el-form-item>
                    <el-form-item label="碎石1" prop="macadamOne">
                        <el-input
                            v-model="matchformRowValue.macadamOne" placeholder="请输入"
                        />
                    </el-form-item>
                    <el-form-item label="碎石2" prop="macadamTwo">
                        <el-input
                            v-model="matchformRowValue.macadamTwo" placeholder="请输入"
                        />
                    </el-form-item>
                    <el-form-item label="碎石3" prop="macadamThree">
                        <el-input
                            v-model="matchformRowValue.macadamThree" placeholder="请输入"
                        />
                    </el-form-item>
                    <el-form-item label="水" prop="water">
                        <el-input
                            v-model="matchformRowValue.water" placeholder="请输入"
                        />
                    </el-form-item>
                    <el-form-item label="掺加剂" prop="admixture">
                        <el-input
                            v-model="matchformRowValue.admixture" placeholder="请输入"
                        />
                    </el-form-item>
                    <el-form-item label="粉煤灰" prop="coalAsh">
                        <el-input
                            v-model="matchformRowValue.coalAsh" placeholder="请输入"
                        />
                    </el-form-item>
                    <el-form-item label="矿渣粉" prop="slagPowder">
                        <el-input
                            v-model="matchformRowValue.slagPowder" placeholder="请输入"
                        />
                    </el-form-item>
                    <el-form-item label="坍落度" prop="slumps">
                        <el-input
                            v-model="matchformRowValue.slumps" placeholder="请输入"
                        />
                    </el-form-item>

                    <el-form-item label="单位体积重" prop="bulkDensity">
                        <el-input
                            v-model="matchformRowValue.bulkDensity	" placeholder="请输入"
                        />
                    </el-form-item>
                    <el-form-item label="28天抗压强度" prop="compressiveStrength">
                        <el-input
                            v-model="matchformRowValue.compressiveStrength	" placeholder="请输入"
                        />
                    </el-form-item>
                </el-form>
                <template #footer>
                    <div class="dialog-footer">
                        <el-button size="large" @click="testModal = false">取消</el-button>
                        <el-button v-if="tabsTypeKey === '0'" :loading="saveFormLoading" hc-btn type="primary" @click="saveFormClick">提交</el-button>
                        <el-button v-if="tabsTypeKey === '1'" :loading="saveFormLoading" hc-btn type="primary" @click="matchsaveFormClick">提交</el-button>
                    </div>
                </template>
            </hc-new-dialog>

            <!-- 导入 弹框 -->
            <hc-new-dialog v-model="importModal" :title="tabsTypeKey === '0' ? '导入原材' : '导入配合比'" @close="importModalClose">
                <div class="hc-import-modal-box">
                    <div class="tip-box">
                        <span>请先下载导入模板(</span>
                        <a
                            v-if="tabsTypeKey === '0'"
                            class="text-link"
                            href="https://blade-oss-chongqing.oss-cn-shenzhen.aliyuncs.com/upload/20230822/dbb9c54a1bd831fb972bf9a6e9b2b478.xlsx"
                            target="_blank"
                        >原材导入模板</a>
                        <a
                            v-if="tabsTypeKey === '1'"
                            class="text-link"
                            href="https://view.officeapps.live.com/op/view.aspx?src=http%3A%2F%2Fblade-oss-chongqing.oss-cn-shenzhen.aliyuncs.com%2F%2Fupload%2F20230828%2Fa877e37bfc414686fa70470bca1c9cd0.xlsx&wdOrigin=BROWSELINK"
                            target="_blank"
                        >配合比导入模板</a>
                        <span> )，按模板样式编辑后，再点击"选择文件"按钮选择编辑好的文件，并点击底部的"确认导入"按钮即可导入成功!</span>
                    </div>
                    <div class="upload-box">
                        <el-upload
                            ref="uploadRef" v-model:file-list="fileList" :accept="accept" :action="action"
                            :auto-upload="false" :data="addition" :headers="getHeader()" :limit="1"
                            :on-error="handleUploadError" :on-exceed="handleUploadExceed"
                            :on-progress="handleUploadProgress" :on-success="handleUploadFinish"
                        >
                            <template #trigger>
                                <el-button :loading="importLoading" type="primary">选择文件</el-button>
                            </template>
                        </el-upload>
                    </div>
                </div>
                <template #footer>
                    <div class="dialog-footer">
                        <el-button size="large" @click="importModal = false">取消</el-button>
                        <el-button
                            :disabled="fileList.length <= 0" :loading="importLoading" hc-btn type="primary"
                            @click="handleImportClick"
                        >
                            确认导入
                        </el-button>
                    </div>
                </template>
            </hc-new-dialog>
        </HcNewCard>
    </div>
</template>

<script setup>
import { onMounted, ref } from 'vue'
import testApi from '~api/gauge/testdata'
import { deepClone, formValidate, getArrValue } from 'js-fast-way'
import { useAppStore } from '~src/store'
import { genFileId } from 'element-plus'
import { getHeader } from 'hc-vue3-ui'
const useAppState = useAppStore()
//全局变量
const projectId = ref(useAppState.getProjectId)
const contractId = ref(useAppState.getContractId)
//渲染完成
onMounted(() => {
    // searchForm.value.type = typeName
    getDataBytype()
})
//类型tab数据和相关处理
const placeTitle = ref('请输入批准文号进行查询')
const tabsTypeKey = ref('0')
const tabsTypeData = ref([
    { key: '0', name: '原材' },
    { key: '1', name: '配合比' },
])
const tableColumn = [
    { key: 'name', name: '材料名称' },
    { key: 'specification', name: '规格型号' },
    { key: 'manufacturers', name: '生产厂商' },
    { key: 'storageSite', name: '存放地点或厂号' },
    { key: 'batchNumber', name: '试验批准文号' },
    { key: 'total', name: '准备数量' },
    { key: 'action', name: '操作', width: '130' },
]
//原材
const tableData = ref([])
//配比
const matchData = ref([])
const matchTableColumn = [
    { key: 'reportNumber', name: '配合比报告编号' },
    { key: 'designStrength', name: '设计强度' },
    { key: 'waterBinderRatio', name: '水胶比' },
    { key: 'cement', name: '水泥' },
    { key: 'sand', name: '砂' },
    { key: 'macadamOne', name: '碎石1' },
    { key: 'macadamTwo', name: '碎石2' },
    { key: 'macadamThree', name: '碎石3' },
    { key: 'water', name: '水' },
    { key: 'admixture', name: '掺加剂' },
    { key: 'coalAsh', name: '粉煤灰' },
    { key: 'slagPowder', name: '矿渣粉' },
    { key: 'slumps', name: '坍落度' },
    { key: 'bulkDensity', name: '单位体积重' },
    { key: 'compressiveStrength', name: '28天抗压强度' },
    { key: 'action', name: '操作', width: '130' },
]
const matchtableLoading = ref(false)
const tabsTypeChange = (item) => {
    tabsTypeKey.value = item?.key
    searchForm.value.type = item?.key
    searchForm.value.current = 1
    getDataBytype()
    if (item?.key === '0') {
        placeTitle.value = '请输入批准文号进行查询'
        action.value = '/api/blade-manager/rawMaterials/importRawMaterialsInfo'
    } else {
        placeTitle.value = '请输入报告编号进行查询'
        action.value = '/api//blade-manager/mixProportion/importMixProportionInfo'
    }

}
//获取原材数据

const getMatchTableData = async () => {
    matchtableLoading.value = true
    const { error, code, data } = await testApi.queryListProp({
        ...searchForm.value,
        projectId:projectId.value,
        contractId:contractId.value,
    })
    //处理数据
    matchtableLoading.value = false
    if (!error && code === 200) {
        let records = getArrValue(data['records'])
        if (tabsTypeKey.value === '1') {
            matchData.value = records
        }
        searchForm.value.total = data.total || 0
    } else {
        matchData.value = []
        searchForm.value.total = 0
    }
}
//获取配合比数据
const tableLoading = ref(false)
const getTableData = async () => {
    tableLoading.value = true
    const { error, code, data } = await testApi.queryListData({
        ...searchForm.value,
        projectId:projectId.value,
        contractId:contractId.value,
    })
    //处理数据
    tableLoading.value = false
    if (!error && code === 200) {
        let records = getArrValue(data['records'])
        if (tabsTypeKey.value === '0') {
            tableData.value = records
        }
        searchForm.value.total = data.total || 0
    } else {
        tableData.value = []
        searchForm.value.total = 0
    }
}
const getDataBytype = ()=>{
    if (tabsTypeKey.value === '0') {
        getTableData()
    } else {
        getMatchTableData()
    }
}
//搜索表单
const searchForm = ref({
    searchValue:'',
    current: 1, size: 20, total: 0,
})
//分页被点击
const pageChange = ({ current, size }) => {
    searchForm.value.current = current
    searchForm.value.size = size
    getDataBytype()
}

const AddRowClick = ()=>{
    testModal.value = true
    formRowValue.value = {}
    matchformRowValue.value = {}
}


const searchClick = ()=>{
    searchForm.value.current = 1
    getDataBytype()


}
const keyUpEvent = (e)=>{
    if (e.key === 'Enter') {
        searchForm.value.current = 1
        getDataBytype()
    }
}
//新增编辑弹窗
const testModal = ref (false)
const formRowValue = ref({})
const formRowRef = ref(null)
const rulesRow = {
    name: {
        required: false,
        trigger: 'blur',
        message: '请输入材料名称',
    },
    specification: {
        required: false,
        trigger: 'blur',
        message: '请输入规格型号',
    },
    manufacturers: {
        required: false,
        trigger: 'blur',
        message: '请输入生产厂商',
    },
    storageSite: {
        required: false,
        trigger: 'blur',
        message: '请输入存放地点或厂号',
    },
    batchNumber: {
        required: false,
        trigger: 'blur',
        message: '请输入试验批准文号',
    },
    total: {
        required: false,
        trigger: 'blur',
        message: '请输入准备数量',
    },
}
const matchformRowRef = ref(null)
const matchrulesRow = {
    reportNumber: {
        required: false,
        trigger: 'blur',
        message: '请输入',
    },
    designStrength: {
        required: false,
        trigger: 'blur',
        message: '请输入',
    },
    waterBinderRatio: {
        required: false,
        trigger: 'blur',
        message: '请输入',
    },
    cement: {
        required: false,
        trigger: 'blur',
        message: '请输入',
    },
    sand: {
        required: false,
        trigger: 'blur',
        message: '请输入',
    },
    macadamOne: {
        required: false,
        trigger: 'blur',
        message: '请输入',
    },
    macadamTwo: {
        required: false,
        trigger: 'blur',
        message: '请输入',
    },
    macadamThree: {
        required: false,
        trigger: 'blur',
        message: '请输入',
    },
    water: {
        required: false,
        trigger: 'blur',
        message: '请输入',
    },
    admixture: {
        required: false,
        trigger: 'blur',
        message: '请输入',
    },
    coalAsh: {
        required: false,
        trigger: 'blur',
        message: '请输入',
    },
    slagPowder: {
        required: false,
        trigger: 'blur',
        message: '请输入',
    },
    slumps: {
        required: false,
        trigger: 'blur',
        message: '请输入',
    },
    bulkDensity: {
        required: false,
        trigger: 'blur',
        message: '请输入',
    },
    compressiveStrength: {
        required: false,
        trigger: 'blur',
        message: '请输入',
    },
}
const matchformRowValue = ref({})
const testModalClose = ()=>{
    testModal.value = false
}
const handleLevelEdit = (row)=>{
    console.log(row, '编辑')
    testModal.value = true
    const rows = deepClone(row)
    formRowValue.value = rows
}
const handleLevelDelete = async ({ item }, resolve) => {
    await delData(item.id)
    resolve()
}
//原材删除请求
const delData = async (id) => {
    const { error, code } = await testApi.delData({ ids: id }, false)
    //判断状态
    if (!error && code === 200) {
        window?.$message?.success('删除成功')
        getDataBytype()
    } else {
        window?.$message?.error('删除失败')
    }
}
//配合比删除请求
const matchdelData = async (id) => {
    const { error, code } = await testApi.matchdelData({ ids: id }, false)
    //判断状态
    if (!error && code === 200) {
        window?.$message?.success('删除成功')
        getDataBytype()
    } else {
        window?.$message?.error('删除失败')
    }
}
//配合比
const handmatchEdit = (row)=>{
    console.log(row, '编辑')
    testModal.value = true
    const rows = deepClone(row)
    matchformRowValue.value = rows
}
const handmathDelete = async ({ item }, resolve) => {
    await matchdelData(item.id)
    resolve()
}
const saveFormLoading = ref(false)
const saveFormClick = async ()=>{
    console.log('提交')
    const validate = await formValidate(formRowRef.value)
    if (validate) {
        const form = formRowValue.value
        form.projectId = projectId.value
        form.contractId = contractId.value
        if (form.id) {
            saveFormLoading.value = true
            const { error, code } = await testApi.updateSave(form, false)
            //判断状态
            saveFormLoading.value = false
            if (!error && code === 200) {
                testModal.value = false
                window?.$message?.success('保存成功')
                getDataBytype()
            } else {
                window?.$message?.error('保存失败')
            }
        } else {
            saveFormLoading.value = true
            const { error, code } = await testApi.addSave(form, false)
            //判断状态
            saveFormLoading.value = false
            if (!error && code === 200) {
                testModal.value = false
                window?.$message?.success('新增成功')
                getDataBytype()
            } else {
                window?.$message?.error('新增失败')
            }
        }
    }
}
const matchsaveFormClick = async ()=>{
    console.log('提交配合比')
    const validate = await formValidate(matchformRowRef.value)
    if (validate) {
        const form = matchformRowValue.value
        form.projectId = projectId.value
        form.contractId = contractId.value
        if (form.id) {
            saveFormLoading.value = true

            const { error, code } = await testApi.matchupdateSave(form, false)
            //判断状态
            saveFormLoading.value = false
            if (!error && code === 200) {
                testModal.value = false
                window?.$message?.success('保存成功')
                getDataBytype()
            } else {
                window?.$message?.error('保存失败')
            }
        } else {
            saveFormLoading.value = true
            const { error, code } = await testApi.matchaddSave(form, false)
            //判断状态
            saveFormLoading.value = false
            if (!error && code === 200) {
                testModal.value = false
                window?.$message?.success('新增成功')
                getDataBytype()
            } else {
                window?.$message?.error('新增失败')
            }
        }
    }
}
//导入弹窗
const importModal = ref(false)
const importModalClose = ()=>{
    importModal.value = false
}
// const importModalClick = ()=>{
//     importModal.value = true
// }

//上传配置
const uploadRef = ref(null)
const addition = ref({})
const fileList = ref([])
const action = ref('/api/blade-manager/rawMaterials/importRawMaterialsInfo')
const accept = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel'

//导入
const importLoading = ref(false)
const importModalClick = () => {
    addition.value = {
        projectId: projectId.value,
        contractId: contractId.value,

    }
    importLoading.value = false
    importModal.value = true
}

//上传一个文件时，重置
const handleUploadExceed = (files) => {
    uploadRef.value?.clearFiles()
    const file = files[0]
    file.uid = genFileId()
    uploadRef.value?.handleStart(file)
}

//确认导入
const handleImportClick = () => {
    uploadRef.value?.submit()
}
//上传中
const handleUploadProgress = () => {
    importLoading.value = true
}
//上传完成
const handleUploadFinish = () => {
    importLoading.value = false
    importModal.value = false
    window?.$message?.success('导入成功')
    uploadRef.value?.clearFiles()
    getDataBytype()
}
//上传失败
const handleUploadError = (err) => {
let myError = err.toString()//转字符串
myError = myError.replace('UploadAjaxError: ', '') // 去掉前面的" Error: "
myError = JSON.parse(myError)//转对象
    window?.$message?.error(myError.msg)
    importLoading.value = false
}
</script>

<style lang='scss' scoped>
.hc-layout-box {
    position: relative;
    height: 100%;
}
</style>
