<template>
    <div class="page-container column-container">
        <section class="list-part-container">
            <!-- 搜索区域 -->
            <el-form class="list-search-container" :inline="true">
                <el-form-item label="客户：">
                    {{ currentProduct.companyAlias }}
                </el-form-item>
                <el-form-item label="图号：">
                    {{ currentProduct.drawingNumber }}
                </el-form-item>
                <el-form-item label="规格：">
                    {{ currentProduct.specification }}
                </el-form-item>
                <el-form-item label="产品描述：">
                    {{ currentProduct.description }}
                </el-form-item>
                <el-form-item>

                </el-form-item>
                <el-form-item class="section-title" label="工艺版本：">
                    <el-select-v2 v-model="currentTechnological.id" :options="technologicalProcessList" placeholder="请选择版本"
                        @change="handelTechnological" style="width: 200px" />
                </el-form-item>
                <el-form-item class="section-title" label="当前工序：">
                    <el-select-v2 v-model="technologicalDetailId" clearable :options="technologicalProcessDetailsList"
                        placeholder="请选择工序" style="width: 200px" @change="handleDetailsChange" />


                </el-form-item>
            </el-form>

        </section>
        <div class="page-container row-container">
            <section class="list-part-container" style="flex: 4">
                <div class="list-btns-container">
                    <el-button type="primary" icon="Plus" v-hasPermi="['business:electronicDrawings:add']"
                        @click="handelUpload()">上传
                    </el-button>
                </div>
                <div class="page-container form-container">


                    <!-- 列表区 -->
                    <div class="el-table-container">
                        <el-table ref="equipmentTable" v-loading="loading" row-key="id"
                            @current-change="handleSelectionChange" :data="drawingList" height="600px">
                            <!-- <el-table-column type="selection" width="40" align="center" /> -->
                            <el-table-column type="index" label="行号" width="50" align="center" />

                            <el-table-column label="图纸" prop="drawingName" align="center">
                                <template #default="scope">
                                    <el-button link type="primary">{{
                                        scope.row.drawingName }}</el-button>
                                </template>
                            </el-table-column>
                            <el-table-column label="状态" width="80px" prop="status" align="center">
                                <template #default="scope">
                                    <dict-tag :options="drawing_status" :value="scope.row.status" />
                                </template>
                            </el-table-column>
                            <el-table-column label="是否废弃" width="80px" prop="abandoned" align="center">
                                <template #default="scope">
                                    <dict-tag :options="drawing_type" :value="scope.row.abandoned" />
                                </template>
                            </el-table-column>
                            <el-table-column label="制作人" width="100px" prop="producer" align="center" />
                            <el-table-column label="审核人" width="100px" prop="reviewer" align="center" />
                            <el-table-column label="批准人" width="100px" prop="issuer" align="center" />
                            <el-table-column fixed="right" label="操作" align="center" width="280px">
                                <template #default="scope">
                                    <el-button v-if="scope.row.status == 0 && scope.row.abandoned == 0" link type="primary"
                                        v-hasPermi="['business:electronicDrawings:examine']"
                                        @click="handlePreview(scope.row)">审核
                                    </el-button>
                                    <el-button v-if="scope.row.status == 1" link type="success" plain
                                        v-hasPermi="['business:electronicDrawings:raift']"
                                        @click="handlePreview(scope.row)">批准</el-button>

                                    <el-upload :action="webHost + '/common/upload'" :headers="headers" :limit="1"
                                        :on-success="handleReplaceSuccess" :on-exceed="handleReplaceExceed"
                                        :before-upload="beforeUpload" :show-file-list="false">
                                        <el-button v-if="scope.row.status == 2 && scope.row.abandoned == 0" link
                                            type="warning" plain
                                            v-hasPermi="['business:electronicDrawings:replace']">替换</el-button>
                                    </el-upload>

                                    <el-button
                                        v-if="(scope.row.status == 0 || scope.row.status == 1) && scope.row.abandoned == 0"
                                        link type="danger" v-hasPermi="['business:electronicDrawings:NG']"
                                        @click="handleDrawingNG(scope.row)">NG
                                    </el-button>
                                    <el-button v-if="scope.row.status == 2 && scope.row.abandoned == 0" link type="danger"
                                        v-hasPermi="['business:electronicDrawings:remove']"
                                        @click="handleDrawingRemove(scope.row)">作废
                                    </el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                    </div>
                    <!-- 分页 -->
                    <pagination v-show="total > 0" :total="total" v-model:page="queryparams.pageNum"
                        v-model:limit="queryparams.pageSize" @pagination="getDrawing" />
                </div>
            </section>

            <section class="list-part-container" style="flex: 3">
                <el-form class="list-search-container" :model="draform" ref="queryRef" :inline="true"
                    style="margin-right: 0px">
                    <el-form-item class="section-title" label="预览" />
                    <el-form-item style="float: inline-end;margin-top: 8px;">
                        <el-button link type="primary" v-hasPermi="['business:product:remove']"
                            @click="openDrawing">全屏预览</el-button>
                    </el-form-item>
                </el-form>
                <iframe :src="drawingUrl" frameborder="no" style="width: 100%; height: 100%" scrolling="auto" />
            </section>

        </div>

        <!-- 添加图纸对话框 -->
        <el-dialog title="上传文件" v-model="open" width="500px" append-to-body>
            <el-form ref="drawingRef" :model="form" :rules="rules" label-width="120px" v-loading="formLoading">


                <el-form-item label="工序：" prop="technologicalProcessDetailId">
                    <el-select-v2 v-model="form.technologicalProcessDetailId" clearable
                        :options="technologicalProcessDetailsList" placeholder="请选择工序：" @change="handleDetailsFormChange"
                        style="width: 200px" />
                </el-form-item>

                <el-form-item label="标识：" prop="identification">
                    <el-checkbox v-model="form.identification" label="重" size="large" />
                    <el-checkbox v-model="form.markD" label="D标识" size="large" />
                </el-form-item>

                <el-form-item label="上传文件：" prop="url">
                    <el-input disabled v-model="form.url" placeholder="上传文件">
                        <template #append>
                            <el-upload :disabled="!form.technologicalProcessDetailId" :action="webHost + '/common/upload'"
                                :headers="headers" :limit="1" :on-success="handleSuccess" :on-exceed="handleExceed"
                                :before-upload="beforeUpload" :show-file-list="false">
                                <el-button icon="Upload"></el-button>
                            </el-upload>
                        </template>
                    </el-input>
                </el-form-item>



            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button :disabled="!form.url" type="primary" @click="submitForm">确 定</el-button>
                    <el-button @click="cancel">取 消</el-button>
                </div>
            </template>
        </el-dialog>

    </div>
</template>
<script setup name="drawingDetails">
import { ref } from "vue";
import { getToken } from '@/utils/auth'
import { getNormalDrawing, getListByName, saveDrawing, drawingNG, replace, drawingRemove } from "@/api/business/drawing";
import useUserStore from '@/store/modules/user'
import { getTechnological, getById } from '@/api/business/product'
import { getTechnologicalProcessDetails } from '@/api/business/technologicalProcessDetail'

const drawingUrl = ref('')
const webHost = import.meta.env.VITE_APP_BASE_API
const fileUrl = import.meta.env.VITE_PREVIEW_API
const hostUrl = import.meta.env.VITE_HOST_URL
const { proxy } = getCurrentInstance();
const { drawing_status } = proxy.useDict("drawing_status");
const { drawing_type } = proxy.useDict("drawing_type");

const total = ref(0)
const route = useRoute();
const coverName = ref("")
const currentProduct = ref({})
const currentTechnological = ref({})
const formLoading = ref(false)
const currentTechnologicalDetail = ref({})
const technologicalProcessList = ref([])
const technologicalProcessDetailsList = ref([])
const technologicalDetailId = ref(null)
const open = ref(false)
const draform = ref({})
const currentDrawing = ref({})
const replaceForm  = ref({})
const repeatingDrawings = ref([])
const loading = ref(false);
const drawingList = ref([])
const headers = { Authorization: getToken() }
const productId = ref(null)
const technologicalprocessDetailId = ref(null)
const technologicalprocessId = ref(null)
/** 查询对象 */
const data = reactive({
    queryparams: {
        pageNum: 1,
        pageSize: 10,
        technologicalProcessDetailId: null
    },
    form: {
        pageNum: 1,
        pageSize: 10,
        technologicalProcessDetailId: null,
        groupDetailList: [],
        code: "",
        remark: "",
        type: false
    },
    rules: {
        technologicalProcessDetailId: [{ required: true, message: "工序不能为空", trigger: "blur" }],
    },
});
const { form, rules, queryparams } = toRefs(data);

function getList() {
    console.log(route.params)
    // 解析查询字符串
    // var urlSearchParams = new URLSearchParams(route.params.currentProduct);

    // 将 URLSearchParams 对象转换为普通对象
    // var paramsObject = Object.fromEntries(urlSearchParams);

    // currentProduct.value = paramsObject



    productId.value = route.params.productId
    technologicalprocessId.value = route.params.productProcessId
    if (route.params.processDetailId) {
        console.log(route.params.processDetailId)
        technologicalprocessDetailId.value = route.params.processDetailId
    }
    //查询产品
    getById(productId.value).then(resMsg => {
        if (resMsg.code == 200) {
            currentProduct.value = resMsg.data
        }
    })

    //查询工艺版本
    getTechnological({ productId: productId.value }).then(res => {
        if (res.code == 200) {
            technologicalProcessList.value = res.data
            //版本下拉框默认值
            currentTechnological.value.id = technologicalprocessId.value
            if (technologicalprocessDetailId.value !== undefined && technologicalprocessDetailId.value !== null && technologicalprocessDetailId.value !== 'undefined') {
                technologicalDetailId.value = technologicalprocessDetailId.value
                currentTechnologicalDetail.value.id = technologicalprocessDetailId.value
            }
            //查询工艺工序
            getTechnologicalProcessDetails({ technologicalProcessId: currentTechnological.value.id }).then(response => {
                if (response.code == 200) {
                    technologicalProcessDetailsList.value = response.data
                    getDrawing()
                }
            })
        }
    })

}
function handleDetailsFormChange() {
    console.log(form.value.technologicalProcessDetailId)
    console.log(technologicalDetailId.value, 123123)
    technologicalDetailId.value = form.value.technologicalProcessDetailId
}

function openDrawing() {
    window.open(drawingUrl.value)

    // console.log(fileUrl + hostUrl + webHost + row.url,9797)
    // console.log(document.location.protocol)
}

function handleSelectionChange(row) {
    currentDrawing.value = row
    console.log(hostUrl)
    console.log(document.location)
    drawingUrl.value = fileUrl + encodeURIComponent(Base64.encode(document.location.origin + webHost + row.url))

}

/**文件数量超出的回调 */
function handleExceed(files) {
    form.value.url = files[0].url
}
/** 文件上传前的 回调事件 */
function beforeUpload(file) {
    formLoading.value = true
    const allowedTypes = ['application/pdf'];
    const isAllowed = allowedTypes.includes(file.type);
    if (!isAllowed) {
        proxy.$modal.msgError('只能上传 PDF 格式的文件!')
        formLoading.value = false
        return false
    }

}
function handelUpload() {
    open.value = true
    form.value.technologicalProcessDetailId = currentTechnologicalDetail.value.id
    console.log(currentTechnologicalDetail.value.id)
    console.log(technologicalDetailId.value)
}
/**获取图纸列表 */
function getDrawing() {
    console.log(currentTechnological.value.id)
    queryparams.value.technologicalProcessId = currentTechnological.value.id
    if (currentTechnologicalDetail.value.id !== undefined && currentTechnologicalDetail.value.id !== 'undefined') {
        queryparams.value.technologicalProcessDetailId = currentTechnologicalDetail.value.id

    }

    getNormalDrawing(queryparams.value).then(res => {
        if (res.code == 200) {
            drawingList.value = res.rows
            console.log(res.rows)
            total.value = res.total
        }
    })
}
/**上传成功回调 */
function handleSuccess(row) {
    form.value.url = row.fileName
    var fileDrawing = {}
    fileDrawing.drawingName = row.originalFilename
    fileDrawing.technologicalProcessDetailId = currentTechnologicalDetail.value.id

    getListByName(fileDrawing).then(res => {
        // debugger;
        if (res.code == 200) {
            console.log(res, "数据库查询")
            repeatingDrawings.value = res.data
            if (repeatingDrawings.value.length == 0) {

                coverName.value = row.originalFilename
                formLoading.value = false
            } else {
                //判断重名文件状态是否已发行需要替换
                if (repeatingDrawings.value[0].status == 0) {
                    proxy.$modal.msgWarning("待审核中已有相同文件");
                    var item = {}
                    item = repeatingDrawings.value[0]
                    item.parentId = currentDrawing.value.id
                    item.id = null
                    item.url = replaceForm.value.url
                    item.drawingName = fileDrawing.drawingName
                    item.technologicalProcessDetailId = fileDrawing.technologicalProcessDetailId
                    handleReplace(item)
                } else {
                    proxy.$modal.msgError("已有相同文件，请修改后重新上传");
                    open.value = false
                }
            }
        }
    })
}


/**文件数量超出的回调 */
function handleReplaceExceed(files) {
    replaceForm.value.url = files[0].url
}
/**上传成功回调 */
function handleReplaceSuccess(row) {
    replaceForm.value.url = row.fileName
    var fileDrawing = {}
    fileDrawing.drawingName = row.originalFilename
    fileDrawing.technologicalProcessDetailId = currentTechnologicalDetail.value.id
    var item = {}
    item.parentId = currentDrawing.value.id
    item.id = null
    item.url = replaceForm.value.url
    item.drawingName = fileDrawing.drawingName
    item.technologicalProcessDetailId = fileDrawing.technologicalProcessDetailId
    handleReplace(item)

}
function submitForm() {
    proxy.$refs["drawingRef"].validate((valid) => {
        console.log(proxy.$refs["drawingRef"])
        if (valid) {
            open.value = false
            saveDrawingDetail()
        }
    });
}
/**保存方法 */
function saveDrawingDetail() {
    if (currentTechnologicalDetail.value.id !== undefined && currentTechnologicalDetail.value.id !== null && currentTechnologicalDetail.value.id !== 'undefined') {
        form.value.technologicalProcessDetailId = currentTechnologicalDetail.value.id
    }
    form.value.drawingName = coverName.value

    var itemList = []
    itemList.push(form.value)
    saveDrawing(itemList).then(res => {
        if (res.code == 200) {
            reset();
            getList();
            formLoading.value = false

        }
    })
}
/**审核 */
function handlePreview(row) {
    var drawing = []
    drawing.push(row)
    saveDrawing(drawing).then(res => {
        if (res.code == 200) {
            proxy.$modal.msgSuccess("审核通过");
            reset()
            getList();
        }
    })
}
function reset() {
    form.value = {
        pageNum: 1,
        pageSize: 10,
        code: null,
        remark: null,
        groupDetailList: [],
        url: null,
        drawingName: null,
        type: false
    };
    currentProduct.value = {}
    currentTechnologicalDetail.value = {}
    currentTechnological.value = {}
    coverName.value = ''
    repeatingDrawings.value = []
    proxy.resetForm("drawingRef");
}
// 取消按钮
function cancel() {
    open.value = false
    reset()
}
/**版本change事件 */
function handelTechnological(row) {
    getDrawing()
}
/**工序选择change事件 */
function handleDetailsChange(row) {
    currentTechnologicalDetail.value.id = technologicalDetailId.value == undefined ? null : technologicalDetailId.value
    getDrawing()
}
/**NG电子图纸 */
function handleDrawingNG(row) {
    console.log(row)
    proxy.$modal
        .confirm("是否确认NG？")
        .then(function () {
            var itemList = []
            itemList.push(row)
            return drawingNG(itemList);
        })
        .then(() => {
            reset()
            getList();
            open.value = false
            proxy.$modal.msgSuccess("操作成功");
        })
        .catch(() => { });
}
/**废弃电子图纸 */

function handleDrawingRemove(row) {
    console.log(row)
    proxy.$modal
        .confirm("是否确认作废？")
        .then(function () {
            var itemList = []
            itemList.push(row)
            return drawingRemove(itemList);
        })
        .then(() => {
            reset()
            getList();
            open.value = false
            proxy.$modal.msgSuccess("操作成功");
        })
        .catch(() => { });
}

function handleReplace(row) {
    proxy.$modal
        .confirm("是否确认替换图纸？")
        .then(function () {
            return replace(row);
        })
        .then(() => {
            reset()
            getList();
            open.value = false
            proxy.$modal.msgSuccess("替换成功");
        })
        .catch(() => { });
}

getList()
</script>

<style scoped>
:deep(.el-form-item .el-form-item__label) {
    font-size: 18px !important;
    padding-right: 0 !important;
}

:deep(#list-search-container .el-form-item--default .el-form-item__content) {
    line-height: 32px;
    font-size: 18px;
}
</style>