<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
            <el-form-item prop="startTime">
                <el-date-picker
                    v-model="queryParams.startTime"
                    value-format="yyyy-MM-dd"
                    type="date"
                    placeholder="开始日期"
                    @change="() => queryParams.endTime = ''"
                    style="width: 130px"
                />
            </el-form-item>
            <el-form-item>-</el-form-item>
            <el-form-item prop="endTime">
                <el-date-picker
                    v-model="queryParams.endTime"
                    value-format="yyyy-MM-dd"
                    type="date"
                    placeholder="结束日期"
                    :picker-options="{ disabledDate: (t) => t.getTime() < new Date(queryParams.startTime).getTime() - 86400000}"
                    style="width: 130px"
                />
            </el-form-item>
            <el-form-item  prop="status">
                 <el-select v-model="queryParams.status" placeholder="请选择状态" clearable size="small">
                    <el-option label="已验收" value="1" />
                    <el-option label="未入库" value="2" />
                </el-select>
            </el-form-item>
            <el-form-item  prop="keyWord">
                <el-input
                    v-model="queryParams.keyWord"
                    placeholder="请输入关键词"
                    clearable
                    @keyup.enter.native="handleQuery"
                    maxlength="20"
                />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">查询</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
                <el-button type="warning" icon="el-icon-download" size="mini" @click="handleExport">导出</el-button>
            </el-form-item>
        </el-form>

        <el-table v-loading="loading" :data="tableList" ref="multipleTable" border :span-method="objectSpanMethod" :max-height="650">
            <el-table-column label="序号" align="center" width="80" type="index">
                <template scope="scope">
                    <span v-if="scope.$index==0">合计：</span>
                    <span v-else>{{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index }}</span>
                </template>
            </el-table-column>
            <el-table-column label="物资名称" align="center" prop="typeName" :show-overflow-tooltip="true"/>
            <el-table-column label="规格型号" align="center" prop="typeModelName" :show-overflow-tooltip="true"/>
            <el-table-column label="计量单位" align="center" prop="unitName" :show-overflow-tooltip="true"/>
            <el-table-column label="采购数量" align="center" prop="purchaseNum" :show-overflow-tooltip="true">
                <template scope="scope">
                    <!-- 当 manageType 为 '编码' 时，使用可点击的 span -->
                    <span class="clickText" v-if="scope.row.manageType=='0'" @click="openRecords(scope.row)">
                        {{ scope.row.purchaseNum }}
                    </span>
                    <!-- 否则，直接显示数字 -->
                    <span v-else>
                        {{ scope.row.purchaseNum }}
                    </span>
                </template>
            </el-table-column>
            <el-table-column label="验收合格数量" align="center" prop="passNum" :show-overflow-tooltip="true">
                <template scope="scope">
                    <!-- 当 manageType 为 '编码' 时，使用可点击的 span -->
                    <span class="clickText" v-if="scope.row.manageType=='0'" @click="openAcceptRecords(scope.row)">
                        {{ scope.row.passNum }}
                    </span>
                    <!-- 否则，直接显示数字 -->
                    <span v-else>
                        {{ scope.row.passNum }}
                    </span>
                </template>
            </el-table-column>
            <el-table-column label="未验收数量" align="center" prop="notPassNum" :show-overflow-tooltip="true"/>
            <el-table-column label="入库数量" align="center" prop="inputNum" :show-overflow-tooltip="true">
                <template scope="scope">
                    <!-- 当 manageType 为 '编码' 时，使用可点击的 span -->
                    <span class="clickText" v-if="scope.row.manageType=='0'" @click="openInBoundRecords(scope.row)">
                        {{ scope.row.inputNum }}
                    </span>
                    <!-- 否则，直接显示数字 -->
                    <span v-else>
                        {{ scope.row.inputNum }}
                    </span>
                </template>
            </el-table-column>
            <el-table-column label="待入库数量" align="center" prop="pendingInputNum" :show-overflow-tooltip="true">
                <template scope="scope">
                    <!-- 当 manageType 为 '编码' 时，使用可点击的 span -->
                    <span class="clickText" v-if="scope.row.manageType=='0'" @click="openWaitRecords(scope.row)">
                        {{ scope.row.pendingInputNum }}
                    </span>
                    <!-- 否则，直接显示数字 -->
                    <span v-else>
                        {{ scope.row.pendingInputNum }}
                    </span>
                </template>
            </el-table-column>
            <el-table-column label="采购价格(含税)" align="center" prop="purchasePrice" :show-overflow-tooltip="true"/>
            <el-table-column label="采购价格(不含税)" align="center" prop="purchasePriceNoTax" :show-overflow-tooltip="true"/>
            <el-table-column label="物资厂家" align="center" prop="supplierName" :show-overflow-tooltip="true"/>
            <el-table-column label="到货时间" align="center" prop="purchaseTime" :show-overflow-tooltip="true"/>
            <el-table-column label="验收时间" align="center" prop="passTime" :show-overflow-tooltip="true"/>
            <el-table-column label="入库时间" align="center" prop="inputTime" :show-overflow-tooltip="true"/>
            <el-table-column label="入库人员" align="center" prop="inputUser" :show-overflow-tooltip="true"/>
            <el-table-column label="采购单号" align="center" prop="inputCode" :show-overflow-tooltip="true"/>
            <el-table-column label="相关配套资料" align="center" width="120" >
                <template slot-scope="scope">
                    <div
                        style="color: red; cursor: pointer"
                        @click="openFileDialog(scope.row)"
                    >
                        报告管理
                    </div>
                </template>
            </el-table-column>
        </el-table>

        <pagination
            v-show="total>0"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getList"
        />

        <!-- 采购数量弹窗 -->
        <el-dialog :title="title" :visible.sync="openRecord" width="1200px" append-to-body>
            <el-form :model="dialogQuery" ref="dialogQuery" size="small" :inline="true" label-width="80px">
                <el-form-item label="关键字" prop="keyWord">
                    <el-input
                        v-model="dialogQuery.keyWord"
                        placeholder="请输入关键字"
                        clearable :maxlength="30"
                        style="width: 240px"/>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary"
                        icon="el-icon-search" size="mini"
                        @click="handleDialogQuery"
                        >查询</el-button>
                </el-form-item>
                <el-form-item>
                    <el-button
                        icon="el-icon-refresh"
                        size="mini"
                        @click="resetDialogQuery"
                        >重置</el-button>
                </el-form-item>
                <el-form-item>
                    <el-button
                        type="warning"
                        icon="el-icon-download"
                        size="mini"
                        @click="handleDialogExport"
                        >导出</el-button>
                </el-form-item>
            </el-form>

            <el-table v-loading="loading" :data="dialogList" height="500px">
                <el-table-column label="序号" align="center" width="80" type="index" :index="indexContinuation(dialogQuery.pageNum, dialogQuery.pageSize)">
                </el-table-column>
                <el-table-column label="机具名称" align="center" prop="typeName" :show-overflow-tooltip="true"/>
                <el-table-column label="规格型号" align="center" prop="typeModelName" :show-overflow-tooltip="true"/>
                <el-table-column label="设备编码" align="center" prop="maCode" :show-overflow-tooltip="true"/>
                <el-table-column label="采购价格（含税）" align="center" prop="purchasePrice" :show-overflow-tooltip="true"/>
                <el-table-column label="采购价格（不含税）" align="center" prop="purchasePriceNoTax" :show-overflow-tooltip="true"/>
            </el-table>
            <pagination
                v-show="dialogTotal > 0"
                :total="dialogTotal"
                :page.sync="dialogQuery.pageNum"
                :limit.sync="dialogQuery.pageSize"
                @pagination="getDialogDataList"
                />
        </el-dialog>

        <!-- 验收合格数量弹窗 -->
        <el-dialog :title="title" :visible.sync="openAcceptRecord" width="1200px" append-to-body>
            <el-form :model="dialogAcceptQuery" ref="dialogAcceptQuery" size="small" :inline="true" label-width="80px">
                <el-form-item label="关键字" prop="keyWord">
                    <el-input
                        v-model="dialogAcceptQuery.keyWord"
                        placeholder="请输入关键字"
                        clearable :maxlength="30"
                        style="width: 240px"/>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary"
                        icon="el-icon-search" size="mini"
                        @click="handleAcceptQuery"
                        >查询</el-button>
                </el-form-item>
                <el-form-item>
                    <el-button
                        icon="el-icon-refresh"
                        size="mini"
                        @click="resetAcceptQuery"
                        >重置</el-button>
                </el-form-item>
                <el-form-item>
                    <el-button
                        type="warning"
                        icon="el-icon-download"
                        size="mini"
                        @click="handleAcceptExport"
                        >导出</el-button>
                </el-form-item>
            </el-form>

            <el-table v-loading="loading" :data="dialogAcceptList" height="500px">
                <el-table-column label="序号" align="center" width="80" type="index" :index="indexContinuation(dialogQuery.pageNum, dialogQuery.pageSize)">
                </el-table-column>
                <el-table-column label="机具名称" align="center" prop="typeName" :show-overflow-tooltip="true"/>
                <el-table-column label="规格型号" align="center" prop="typeModelName" :show-overflow-tooltip="true"/>
                <el-table-column label="设备编码" align="center" prop="maCode" :show-overflow-tooltip="true"/>
                <el-table-column label="采购价格（含税）" align="center" prop="purchasePrice" :show-overflow-tooltip="true"/>
                <el-table-column label="采购价格（不含税）" align="center" prop="purchasePriceNoTax" :show-overflow-tooltip="true"/>
            </el-table>
            <pagination
                v-show="dialogTotal > 0"
                :total="dialogTotal"
                :page.sync="dialogAcceptQuery.pageNum"
                :limit.sync="dialogAcceptQuery.pageSize"
                @pagination="getDialogAcceptDataList"
                />
        </el-dialog>

        <!-- 入库数量弹窗 -->
        <el-dialog :title="title" :visible.sync="openInBoundRecord" width="1200px" append-to-body>
            <el-form :model="dialogInBoundQuery" ref="dialogInBoundQuery" size="small" :inline="true" label-width="80px">
                <el-form-item label="关键字" prop="keyWord">
                    <el-input
                        v-model="dialogInBoundQuery.keyWord"
                        placeholder="请输入关键字"
                        clearable :maxlength="30"
                        style="width: 240px"/>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary"
                        icon="el-icon-search" size="mini"
                        @click="handleInBoundQuery"
                        >查询</el-button>
                </el-form-item>
                <el-form-item>
                    <el-button
                        icon="el-icon-refresh"
                        size="mini"
                        @click="resetInBoundQuery"
                        >重置</el-button>
                </el-form-item>
                <el-form-item>
                    <el-button
                        type="warning"
                        icon="el-icon-download"
                        size="mini"
                        @click="handleInBoundExport"
                        >导出</el-button>
                </el-form-item>
            </el-form>

            <el-table v-loading="loading" :data="dialogInBoundList" height="500px">
                <el-table-column label="序号" align="center" width="80" type="index" :index="indexContinuation(dialogQuery.pageNum, dialogQuery.pageSize)">
                </el-table-column>
                <el-table-column label="机具名称" align="center" prop="typeName" :show-overflow-tooltip="true"/>
                <el-table-column label="规格型号" align="center" prop="typeModelName" :show-overflow-tooltip="true"/>
                <el-table-column label="设备编码" align="center" prop="maCode" :show-overflow-tooltip="true"/>
                <el-table-column label="采购价格（含税）" align="center" prop="purchasePrice" :show-overflow-tooltip="true"/>
                <el-table-column label="采购价格（不含税）" align="center" prop="purchasePriceNoTax" :show-overflow-tooltip="true"/>
            </el-table>
            <pagination
                v-show="dialogTotal > 0"
                :total="dialogTotal"
                :page.sync="dialogInBoundQuery.pageNum"
                :limit.sync="dialogInBoundQuery.pageSize"
                @pagination="getDialogInBoundDataList"
                />
        </el-dialog>

        <!-- 待入库数量弹窗 -->
        <el-dialog :title="title" :visible.sync="openWaitRecord" width="1200px" append-to-body>
            <el-form :model="dialogWaitQuery" ref="dialogWaitQuery" size="small" :inline="true" label-width="80px">
                <el-form-item label="关键字" prop="keyWord">
                    <el-input
                        v-model="dialogWaitQuery.keyWord"
                        placeholder="请输入关键字"
                        clearable :maxlength="30"
                        style="width: 240px"/>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary"
                        icon="el-icon-search" size="mini"
                        @click="handleWaitQuery"
                        >查询</el-button>
                </el-form-item>
                <el-form-item>
                    <el-button
                        icon="el-icon-refresh"
                        size="mini"
                        @click="resetWaitQuery"
                        >重置</el-button>
                </el-form-item>
                <el-form-item>
                    <el-button
                        type="warning"
                        icon="el-icon-download"
                        size="mini"
                        @click="handleWaitExport"
                        >导出</el-button>
                </el-form-item>
            </el-form>

            <el-table v-loading="loading" :data="dialogWaitList" height="500px">
                <el-table-column label="序号" align="center" width="80" type="index" :index="indexContinuation(dialogQuery.pageNum, dialogQuery.pageSize)">
                </el-table-column>
                <el-table-column label="机具名称" align="center" prop="typeName" :show-overflow-tooltip="true"/>
                <el-table-column label="规格型号" align="center" prop="typeModelName" :show-overflow-tooltip="true"/>
                <el-table-column label="设备编码" align="center" prop="maCode" :show-overflow-tooltip="true"/>
                <el-table-column label="采购价格（含税）" align="center" prop="purchasePrice" :show-overflow-tooltip="true"/>
                <el-table-column label="采购价格（不含税）" align="center" prop="purchasePriceNoTax" :show-overflow-tooltip="true"/>
            </el-table>
            <pagination
                v-show="dialogTotal > 0"
                :total="dialogTotal"
                :page.sync="dialogWaitQuery.pageNum"
                :limit.sync="dialogWaitQuery.pageSize"
                @pagination="getDialogWaitDataList"
                />
        </el-dialog>

        <el-dialog title="报告管理" :visible.sync="open" width="900px" append-to-body>
            <el-table :data="fileDataList" width="100%" height="350px">
                <el-table-column label="序号" type="index" width="55" align="center" />
                <el-table-column label="报告类型" align="center" prop="dictLabel" :show-overflow-tooltip="true" />
                <el-table-column label="类型名称" align="center" :show-overflow-tooltip="true">
                    <template>
                        <div>{{ this.rowData.maTypeName }}</div>
                    </template>
                </el-table-column>
                <el-table-column label="规格型号" align="center" :show-overflow-tooltip="true">
                    <template>
                        <div>{{ this.rowData.typeName }}</div>
                    </template>
                </el-table-column>
                <!-- <el-table-column label="报告日期" align="center" prop="orgName" :show-overflow-tooltip="true"/>
                <el-table-column label="截止有效期" align="center" prop="orgName" :show-overflow-tooltip="true"/> -->
                <el-table-column label="操作" align="center" width="100">
                    <template slot-scope="scope">
                        <div style="display: flex; align-items: center; justify-content: space-between">
                            <el-upload
                                ref="upload"
                                :headers="upload.headers"
                                :action="upload.url"
                                :show-file-list="false"
                                accept=".png, .jpg, .jpeg, .pdf, .doc, .docx"
                                :on-success="
                                    (response, file, fileList) => handleFileSuccess(scope.row, response, file, fileList)
                                "
                                :auto-upload="true"
                                :before-upload="file => beforeUpload(scope.row, file)"
                            >
                                <el-button size="mini" type="text" @click="beforeFileUpload(scope.row)">上传</el-button>
                            </el-upload>

                            <el-button
                                size="mini"
                                type="text"
                                @click="picturePreviewFile(scope.row)"
                                v-if="scope.row.fileListTemp != 0"
                                style="margin-left: 20px"
                            >
                                查看
                            </el-button>
                        </div>
                    </template>
                </el-table-column>
            </el-table>
            <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleSaveFile">保存</el-button>
        </el-dialog>

        <!-- 图片查看弹窗 -->
        <el-dialog :visible.sync="dialogVisible" width="800px">
            <img width="100%" height="500px" :src="dialogImageUrl" />
        </el-dialog>

        <!-- 文件查看列表 -->
        <el-dialog title="文件列表" :visible.sync="dialogVisibleFile" width="500px" height="500px">
            <el-table :data="fileListInfo" width="100%" height="350px">
                <el-table-column label="序号" type="index" width="55" align="center" />
                <el-table-column label="文件名称" align="center" prop="name" :show-overflow-tooltip="true" />
                <el-table-column label="操作" align="center">
                    <template slot-scope="scope">
                        <el-button size="mini" type="text" @click="picturePreview(scope.row)" v-if="scope.row.url">
                            查看
                        </el-button>
                        <el-button
                            size="mini"
                            type="text"
                            @click="pictureDelete(scope.row, scope.$index)"
                            v-if="scope.row.url"
                            style="color: red"
                        >
                            删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-dialog>

    </div>
</template>

<script>
    import { getPurChaseReportListApi,getPurChaseReportListNoPageApi,getPurChaseReportDetailsListApi,
             getPurChaseReportSuccessListApi,getPurChaseReportInBoundListApi,getPurChaseReportNotInBoundListApi } from "@/api/report/report";
    import { getToken } from '@/utils/auth'
    import { uploadPurchaseFile, getPurchaseFileList } from '@/api/purchase/goodsAccept'
    import {
        updatePurchaseFileApi
    } from '@/api/purchase/goodsArrived'
    export default {
    name: "GoodsEntryReport",
    data() {
        return {
        // 遮罩层
        loading: false,
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        showHouse: false,
        dateRange:[],
        ids:[],
        // 查询参数
        queryParams: {
            pageNum: 1,
            pageSize: 10,
            status: '',
            keyWord:undefined,
            startTime: '',
            endTime: '',
        },
        // 总条数
        total: 0,
        //表格数据
        tableList: [],
        // 弹出层标题
        title: "",
        //弹窗
        openRecord: false,
        openAcceptRecord: false,
        openInBoundRecord: false,
        openWaitRecord: false,
        dialogList: [], //在库编码设备列表
        dialogAcceptList: [], //验收合格设备列表
        dialogInBoundList: [], //入库设备列表
        dialogWaitList: [], //待入库设备列表
        dialogQuery: {
            pageNum: 1,
            pageSize: 10,
            keyWord: undefined,
        },
        dialogAcceptQuery: {
            pageNum: 1,
            pageSize: 10,
            keyWord: undefined,
        },
        dialogInBoundQuery: {
            pageNum: 1,
            pageSize: 10,
            keyWord: undefined,
        },
        dialogWaitQuery: {
            pageNum: 1,
            pageSize: 10,
            keyWord: undefined,
        },
        dialogTotal: 0,
        // 是否显示弹出层
        taskId:'',
        open: false,
        rowData: {},
        fileDataList: [
            { dictLabel: '合格证', fileType: '0', name: '', url: '', fileList: [], fileListTemp: [] },
            { dictLabel: '型式试验报告', fileType: '1', name: '', url: '', fileList: [], fileListTemp: [] },
            { dictLabel: '出厂检测报告', fileType: '2', name: '', url: '', fileList: [], fileListTemp: [] },
            { dictLabel: '第三方检测报告', fileType: '3', name: '', url: '', fileList: [], fileListTemp: [] },
            { dictLabel: '其他', fileType: '4', name: '', url: '', fileList: [], fileListTemp: [] }
        ],
        fileListInfo: [],
        //图片查看弹窗
        dialogImageUrl: '',
        dialogVisible: false,
        dialogVisibleFile: false,
        //上传
        upload: {
            // 设置上传的请求头部
            headers: { Authorization: 'Bearer ' + getToken() },
            // 上传的地址
            url: process.env.VUE_APP_BASE_API + '/file/upload'
        },
        };
    },
    created() {
        const end = new Date()
        let start = new Date()
        start.setMonth(start.getMonth() - 1)
        this.dateRange = [this.format(start), this.format(end)]
        this.initDefaultDate()
        this.getList()
    },
    methods: {
        //文件管理
        async openFileDialog(row) {
          console.log('1111111', row)
          this.rowData = row;
          this.taskId=this.rowData.taskId;
          console.log("this.rowData.taskId",this.rowData.taskId)
          if(this.rowData.taskId==null||this.rowData.taskId==""||this.rowData.taskId==undefined){
            return;
          }
          this.fileDataList = [
              { dictLabel: '合格证', fileType: '0', name: '', url: '', fileList: [], fileListTemp: [] },
              { dictLabel: '型式试验报告', fileType: '1', name: '', url: '', fileList: [], fileListTemp: [] },
              { dictLabel: '出厂检测报告', fileType: '2', name: '', url: '', fileList: [], fileListTemp: [] },
              { dictLabel: '第三方检测报告', fileType: '3', name: '', url: '', fileList: [], fileListTemp: [] },
              { dictLabel: '其他', fileType: '4', name: '', url: '', fileList: [], fileListTemp: [] }
          ]
          await this.getFileData();
          console.log("this.rowData.bmFileInfos",this.rowData.bmFileInfos)
          if (this.rowData.bmFileInfos == null) {
              if (this.rowData.bmFileInfos.length > 0) {
                  this.rowData.bmFileInfos.forEach(item => {
                      let index = this.fileDataList.findIndex(v => v.fileType == item.fileType)
                      this.fileDataList[index].name = item.name
                      this.fileDataList[index].url = item.url
                      this.fileDataList[index].fileList.push({
                          name: item.name,
                          url: item.url
                      })
                      this.fileDataList[index].fileListTemp.push({
                          name: item.name,
                          url: item.url
                      })
                  })
              }
          } else {
              if (this.rowData.bmFileInfos.length > 0) {
                  this.rowData.bmFileInfos.forEach(item => {
                      let index = this.fileDataList.findIndex(v => v.fileType == item.fileType)
                      this.fileDataList[index].name = item.name
                      this.fileDataList[index].url = item.url
                      this.fileDataList[index].fileList.push({
                          name: item.name,
                          url: item.url
                      })
                      this.fileDataList[index].fileListTemp.push({
                          name: item.name,
                          url: item.url
                      })
                  })
              }
          }
          this.open = true;
        },

        async getFileData() {
            let param = {
                modelId: this.rowData.typeId,
                taskType: 0,
                taskId: this.rowData.taskId
            }
            this.rowData.bmFileInfos = []
            await getPurchaseFileList(param)
                .then(response => {
                  console.log("response.rows",response.rows);
                    if (response.rows.length > 0) {
                        response.rows.forEach(item => {
                                // this.fileDataList[index].fileList.push({
                                //     name:item2.name,
                                //     url:item2.url
                                // })
                                // this.fileDataList[index].fileListTemp.push({
                                //     name:item2.name,
                                //     url:item2.url
                                // })
                                if(item.modelId!=null&&item.modelId!=''&&item.modelId!=undefined){
                                  this.rowData.partId=item.modelId;
                                }
                                const obj = {
                                    taskId: item.taskId,
                                    taskType: item. taskType,
                                    name: item.name,
                                    url: item.url,
                                    modelId: item.modelId,
                                    fileType: item.fileType
                                }
                                this.rowData.bmFileInfos.push(obj)
                                console.log('77777777', this.rowData)
                        })
                    }
                })
                .catch(() => {})
        },

        beforeFileUpload(row) {
            this.rowData.fileType = row.fileType
        },

        beforeUpload(row, file) {
            row.fileList.push(file)
            console.log('6666666', row.fileList)
            if (row.fileList.length > 3) {
                this.$message.warning('最多只能上传三张图片')
                // 删除最后一个文件
                row.fileList.pop()
                return false // 阻止上传
            }
            return true // 允许上传
        },
        // 文件上传成功处理
        handleFileSuccess(row, response, file, fileList) {
            if (response.code == 200) {
                //编辑逻辑
                row.fileListTemp.push({
                    name: response.data.name,
                    url: response.data.url
                })
                let obj = {
                    taskId: this.taskId,
                    taskType: '0',
                    name: response.data.name,
                    url: response.data.url,
                    modelId: this.rowData.partId,
                    fileType: this.rowData.fileType
                    //   "dictLabel": this.rowData.dictLabel,
                }
                //根据文件上传返回更新文件管理弹窗内容
                let index = this.fileDataList.findIndex(v => v.fileType == this.rowData.fileType)
                this.fileDataList[index].name = response.data.name
                this.fileDataList[index].url = response.data.url
                //判断当前上传的文件是否已上传过-再往机具类型数据中插入
                if (this.rowData.bmFileInfos.length > 0) {
                    let index2 = this.rowData.bmFileInfos.findIndex(v => v.fileType == this.rowData.fileType)
                    if (index2 > -1) {
                        //相同类型文件重复上传-替换
                        this.rowData.bmFileInfos.splice(index2, 0, obj)
                    } else {
                        //不存在相同类型文件-添加
                        this.rowData.bmFileInfos.push(obj)
                    }
                } else {
                    this.rowData.bmFileInfos.push(obj)
                }
                uploadPurchaseFile(obj)
                    .then(response => {
                      console.log()
                        this.$modal.msgSuccess('上传成功')
                    })
                    .catch(() => {
                        this.$modal.msgError('上传失败')
                    })
            }
        },

        picturePreviewFile(row) {
            row.fileList = []
            row.fileListTemp.forEach(item => {
                row.fileList.push({
                    name: item.name,
                    url: item.url
                })
            })
            this.fileId = row.fileType
            this.fileListInfo = row.fileListTemp

            this.dialogVisibleFile = true
        },

        //图片查看
        picturePreview(file) {
            this.dialogImageUrl = file.url.replaceAll('#', '%23')
            const parts = file.name.split('.')
            const extension = parts.pop()
            if (
                extension === 'doc' ||
                extension === 'DOC' ||
                extension === 'docx' ||
                extension === 'DOCX' ||
                extension === 'pdf' ||
                extension === 'PDF'
            ) {
                const windowName = file.name
                window.open(file.url, windowName)
            } else {
                this.dialogVisible = true
            }
        },

        //删除图片
        pictureDelete(row, id) {
            let index = id
            this.fileListInfo = this.fileListInfo.filter(item => item.url !== row.url)
            this.fileDataList[this.fileId].fileList = this.fileDataList[this.fileId].fileList.filter(
                item => item.url !== row.url
            )
            this.fileDataList[this.fileId].fileListTemp = this.fileDataList[this.fileId].fileListTemp.filter(
                item => item.url !== row.url
            )
            let bmFiles = []
            this.rowData.bmFileInfos.forEach(item => {
                if (item.fileType != this.fileId) {
                    bmFiles.push(item)
                } else {
                    if (item.url != row.url) {
                        bmFiles.push(item)
                    }
                }
            })
            this.rowData.bmFileInfos = bmFiles
        },

        handleSaveFile(){
            this.$modal
                .confirm('是否确认保存当前信息')
                .then(function () {})
                .then(() => {
                    this.loading = true
                    updatePurchaseFileApi({
                        purchaseCheckDetailsList: [{"bmFileInfos":this.rowData.bmFileInfos}],
                        purchaseCheckInfo: {"taskId":this.taskId}
                    }).then(response => {
                        if (response.code == 200) {
                            this.$modal.msgSuccess('编辑成功')
                        }
                        this.loading = false
                        //关闭页面
                        this.open=false;
                    })
                })
                .catch(() => {
                    this.loading = false
                })
        },

        initDefaultDate() {
          const now = new Date();
          this.queryParams.endTime= this.format(now);
          const oneMonthAgo =new Date(now);
          oneMonthAgo.setMonth(oneMonthAgo.getMonth()-1);
          this.queryParams.startTime=this.format(oneMonthAgo);

        },

        format(date) {
            const y = date.getFullYear()
            const m = String(date.getMonth() + 1).padStart(2, '0')
            const day = String(date.getDate()).padStart(2, '0')
            return `${y}-${m}-${day}`
        },
        // 合并单元格 rowIndex=行数  columnIndex=列数
        // 这里是合并table的除表头外的第一行的第二列 + 除表头外的第二行的第二列
        // 注意列数和行数从 0 开始
        objectSpanMethod ({ row, column, rowIndex, columnIndex }) {
            if (rowIndex === 0 && columnIndex == 0) {
                let rowspan = 1
                let colspan = 4
                return { rowspan, colspan }
            }
            // 解决偏移的重要代码
            // 重点在 else if 判断必须加因为合并单元格数据会出现偏移、
            // 否则如果是 第二行 的 第二列 那么隐藏原有第二行 的 第二列的数据使他隐藏
            else if (rowIndex === 0 && columnIndex < 4) {
                return {
                    rowspan: 0,
                    colspan: 0
                }
            }
        },
        /** 查询列表 */
        async getList() {
            this.loading = true
            const params = {
                keyWord: this.queryParams.keyWord,
                startTime: this.queryParams.startTime,
                endTime: this.queryParams.endTime,
                status: this.queryParams.status,
                pageSize: this.queryParams.pageSize,
                pageNum: this.queryParams.pageNum
            }
            const res = await getPurChaseReportListApi(params)
            if(res.data.rows.length>0){
                this.tableList = res.data.rows;
            }else{
                this.tableList=[]
            }
            this.total = res.data.total;
            let param = {
                keyWord: this.queryParams.keyWord,
                startTime: this.queryParams.startTime,
                endTime: this.queryParams.endTime,
                status: this.queryParams.status,
            }
            const response = await getPurChaseReportListNoPageApi(param)
                let obj = {
                    purchaseNum: response.data.purchaseNum||0,//采购数量
                    passNum: response.data.passNum||0,//验收合格数量
                    notPassNum: response.data.notPassNum||0,//未验收数量
                    inputNum: response.data.inputNum||0,//验收合格数量
                    purchasePrice: response.data.purchasePrice||0,//采购价格(含税)
                    purchasePriceNoTax: response.data.purchasePriceNoTax||0,//采购价格(不含税)
                    pendingInputNum: response.data.pendingInputNum||0,//待入库数量
                }
                this.tableList.unshift(obj)
                this.loading = false

        },
        /** 重置按钮操作 */
        resetQuery() {
            this.resetForm("queryForm");
            const end = new Date()
            let start = new Date()
            start.setMonth(start.getMonth() - 1)
            this.dateRange = [this.format(start), this.format(end)]
            this.queryParams.keyWord=null;
            this.handleQuery();
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.getList();
        },
        handleExport() {
          const formatTime = (date) => {
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            const hours = String(date.getHours()).padStart(2, '0');
            const minutes = String(date.getMinutes()).padStart(2, '0');
            const seconds = String(date.getSeconds()).padStart(2, '0');
            return `${year}${month}${day}_${hours}${minutes}${seconds}`;
          };

          const currentTime = formatTime(new Date());
            this.download(
                "/material/bm_report/exportPurChaseReportList",
                { ...this.queryParams },
                `新购入库报表_${currentTime}.xlsx`
            );
        },
        //查看弹框数据
        openRecords(row) {
            this.openRecord = true
            this.dialogQuery.keyWord = ""
            this.dialogQuery.taskId = row.taskId;
            this.dialogQuery.typeId = row.typeId;
            this.getDialogDataList()
        },
        //验收合格数量
        openAcceptRecords(row) {
            this.openAcceptRecord = true
            this.dialogAcceptQuery.keyWord = ""
            this.dialogAcceptQuery.taskId = row.taskId;
            this.dialogAcceptQuery.typeId = row.typeId;
            this.getDialogAcceptDataList()
        },
        //入库数量
        openInBoundRecords(row) {
            this.openInBoundRecord = true
            this.dialogInBoundQuery.keyWord = ""
            this.dialogInBoundQuery.taskId = row.taskId;
            this.dialogInBoundQuery.typeId = row.typeId;
            this.getDialogInBoundDataList()
        },
        //待入库数量
        openWaitRecords(row) {
            this.openWaitRecord = true
            this.dialogWaitQuery.keyWord = ""
            this.dialogWaitQuery.taskId = row.taskId;
            this.dialogWaitQuery.typeId = row.typeId;
            this.getDialogWaitDataList()
        },
        /** 查询采购数量弹框列表 */
        getDialogDataList() {
            getPurChaseReportDetailsListApi(this.dialogQuery).then((response) => {
                this.dialogList = response.data.rows
                this.dialogTotal = response.data.total
            })
        },
        /** 查询验收合格数量弹框列表 */
        getDialogAcceptDataList() {
            getPurChaseReportSuccessListApi(this.dialogAcceptQuery).then((response) => {
                this.dialogAcceptList = response.data.rows
                this.dialogTotal = response.data.total
            })
        },
        /** 查询入库数量弹框列表 */
        getDialogInBoundDataList() {
            getPurChaseReportInBoundListApi(this.dialogInBoundQuery).then((response) => {
                this.dialogInBoundList = response.data.rows
                this.dialogTotal = response.data.total
            })
        },
        /** 查询待入库数量弹框列表 */
        getDialogWaitDataList() {
            getPurChaseReportNotInBoundListApi(this.dialogWaitQuery).then((response) => {
                this.dialogWaitList = response.data.rows
                this.dialogTotal = response.data.total
            })
        },
        /** 弹框搜索操作 */
        handleDialogQuery() {
            this.dialogQuery.pageNum = 1
            this.getDialogDataList()
        },
        handleAcceptQuery() {
            this.dialogAcceptQuery.pageNum = 1
            this.getDialogAcceptDataList()
        },
        handleInBoundQuery() {
            this.dialogInBoundQuery.pageNum = 1
            this.getDialogInBoundDataList()
        },
        handleWaitQuery() {
            this.dialogWaitQuery.pageNum = 1
            this.getDialogWaitDataList()
        },

        /** 弹框重置操作 */
        resetDialogQuery(){
            this.dialogQuery.keyWord = "";
            this.handleDialogQuery()
        },
        resetAcceptQuery(){
            this.dialogAcceptQuery.keyWord = "";
            this.handleAcceptQuery()
        },
        resetInBoundQuery(){
            this.dialogInBoundQuery.keyWord = "";
            this.handleInBoundQuery()
        },
        resetWaitQuery(){
            this.dialogWaitQuery.keyWord = "";
            this.handleWaitQuery()
        },
        /** 弹框导出操作 */
        handleDialogExport() {
          const formatTime = (date) => {
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            const hours = String(date.getHours()).padStart(2, '0');
            const minutes = String(date.getMinutes()).padStart(2, '0');
            const seconds = String(date.getSeconds()).padStart(2, '0');
            return `${year}${month}${day}_${hours}${minutes}${seconds}`;
          };

          const currentTime = formatTime(new Date());
            this.download(
                'material/bm_report/exportPurChaseReportDetailsList',
                { ...this.dialogQuery},
                `新购入库报表_采购设备_${currentTime}.xlsx`,
            )
        },
        handleAcceptExport() {
          const formatTime = (date) => {
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            const hours = String(date.getHours()).padStart(2, '0');
            const minutes = String(date.getMinutes()).padStart(2, '0');
            const seconds = String(date.getSeconds()).padStart(2, '0');
            return `${year}${month}${day}_${hours}${minutes}${seconds}`;
          };

          const currentTime = formatTime(new Date());
            this.download(
                'material/bm_report/exportPurChaseReportSuccessList',
                { ...this.dialogAcceptQuery},
                `新购入库报表_验收合格设备_${currentTime}.xlsx`,
            )
        },
        handleInBoundExport() {
          const formatTime = (date) => {
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            const hours = String(date.getHours()).padStart(2, '0');
            const minutes = String(date.getMinutes()).padStart(2, '0');
            const seconds = String(date.getSeconds()).padStart(2, '0');
            return `${year}${month}${day}_${hours}${minutes}${seconds}`;
          };

          const currentTime = formatTime(new Date());
            this.download(
                'material/bm_report/exportPurChaseReportInBoundList',
                { ...this.dialogInBoundQuery},
                `新购入库报表_入库设备_${currentTime}.xlsx`,
            )
        },
        handleWaitExport() {
          const formatTime = (date) => {
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            const hours = String(date.getHours()).padStart(2, '0');
            const minutes = String(date.getMinutes()).padStart(2, '0');
            const seconds = String(date.getSeconds()).padStart(2, '0');
            return `${year}${month}${day}_${hours}${minutes}${seconds}`;
          };

          const currentTime = formatTime(new Date());
            this.download(
                'material/bm_report/exportPurChaseReportNotInBoundList',
                { ...this.dialogWaitQuery},
                `新购入库报表_待入库设备_${currentTime}.xlsx`,
            )
        },

    }
    };
</script>

<style lang="scss" scoped>
    .image-type {
        /* 旋转图片 */
        transform: rotate(-90deg);
        /* 确保旋转后的图片不会超出容器 */
        max-width: 100%;
        /* 保持图片的宽高比 */
        width: 40px;
        height: 80px;
    }
    .sign-type{
        width: 80px;
        height: 40px;
    }
    .uploadImg {
        padding-top: 20px;
        display: flex;
        align-items: center;
        justify-content: center;
    }
    .deviceCode {
        margin-top: 10px;
        padding-bottom: 20px;
        font-size: 18px;
    }
    ::v-deep.el-table .fixed-width .el-button--mini {
        width: 60px !important;
        margin-bottom: 10px;
    }
    .clickText {
        color: #02a7f0;
        cursor: pointer;
    }
</style>
