<template>
  <div class="app-container" id="entryDetail">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="90px">
      <el-form-item label="类型规格："  prop="typeId" >
        <el-select v-model="queryParams.typeId" placeholder="请选择类型规格" clearable filterable style="width: 240px">
          <el-option
            v-for="dict in materialModelList"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="出厂日期："  prop="productionTime">
        <el-date-picker
          v-model="queryParams.productionTime"
          placeholder="请选择出厂日期"
          value-format="yyyy-MM-dd"
          type="date">
        </el-date-picker>
      </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-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          size="mini"
          icon="el-icon-back"
          @click="jumpList"
        >新购到货入库</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
        >导出</el-button
        >
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="tableList" ref="multipleTable" row-key="typeId" @selection-change="handleSelectionChange">
      <el-table-column label="序号" align="center" width="80" type="index"></el-table-column>
      <el-table-column label="物资名称" align="center" prop="maTypeName" :show-overflow-tooltip="true"/>
      <el-table-column label="规格型号" align="center" prop="typeName" :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"/>
      <el-table-column label="验收数量" align="center" prop="checkNum" :show-overflow-tooltip="true"/>
      <el-table-column label="已入库数量" align="center" prop="inputNum" :show-overflow-tooltip="true"/>
      <el-table-column label="待入库" align="center" prop="inputNum" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <div>
            {{scope.row.manageType === 0 ? scope.row.bindNum - scope.row.inputNum : scope.row.checkNum - scope.row.inputNum }}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="购置单价(元含税)" align="center" prop="purchaseTaxPrice" :show-overflow-tooltip="true"/>
      <el-table-column label="购置单价（元不含税）" align="center" prop="purchasePrice" :show-overflow-tooltip="true"/>
      <el-table-column label="是否未固定资产" align="center" prop="fixCodeStr" :show-overflow-tooltip="true"/>
      <el-table-column label="出厂日期" align="center" prop="productionTime" :show-overflow-tooltip="true"/>
      <el-table-column label="管理模式" align="center" prop="manageType">
        <template slot-scope="scope">
          <div v-if="scope.row.manageType==0">编码管理</div>
          <div v-if="scope.row.manageType==1">数量管理</div>
        </template>
      </el-table-column>
      <el-table-column label="相关配套资料" align="center" prop="" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <div style="color: #02A7F0;cursor: pointer;" @click="openFileDialog(scope.row)" v-if="scope.row.isExitFile==1">报告管理</div>
          <div style="color: red;cursor: pointer;" @click="openFileDialog(scope.row)" v-if="scope.row.isExitFile==0">报告管理</div>
        </template>
      </el-table-column>
      <el-table-column label="验收结论" align="center" prop="checkResult" :show-overflow-tooltip="true"/>
      <el-table-column label="状态" align="center" prop="status" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.purchase_task_status"
            :value="scope.row.status"
          />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="180" v-if="!isView">
        <template slot-scope="scope">
          <el-button size="mini" type="success" @click="pass(scope.row)" v-if="scope.row.status!=14&&scope.row.status!=19 && scope.row.status != 23">
            入库
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog title="报告管理" :visible.sync="open" width="900px" append-to-body>
      <el-table v-loading="dialogLoading" :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" prop="name" :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" width="100">
          <template slot-scope="scope">
            <div style="display: flex;align-items: center;justify-content: center;">
              <el-upload ref="upload" :limit="3" :headers="upload.headers" v-if="!isView"
                         :action="upload.url" :show-file-list="false" accept=".png, .jpg, .jpeg, .pdf, .doc, .docx"
                         :on-success="handleFileSuccess"   :auto-upload="true"
              >
                <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.url" style="margin-left: 10px;">
                查看
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <!-- 图片查看弹窗 -->
    <el-dialog :visible.sync="dialogVisible" width="500px" height="500px" >
      <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>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <!-- 编码入库 -->
    <el-dialog title="编码入库" :visible.sync="openCode" width="1000px" append-to-body>
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary" size="mini" @click="codeWarehouse">入库</el-button>
        </el-col>
      </el-row>
      <!-- 编码表格添加loading状态 -->
      <el-table
        v-loading="codeLoading"
        :data="codeTableData"
        width="100%"
        height="380px"
        row-key="id"
        @selection-change="codeSelection"
      >
        <el-table-column type="selection" width="55" align="center" v-if="!isView"/>
        <el-table-column label="序号" width="55" align="center">
          <template slot-scope="scope">
            {{ (codeQueryParams.pageNum - 1) * codeQueryParams.pageSize + scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column label="类型名称" prop="typeName" align="center" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <span>{{ codeRowData.maTypeName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="规格型号" prop="type" align="center" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <span>{{ codeRowData.typeName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="设备编码" prop="maCode" align="center" :show-overflow-tooltip="true"></el-table-column>
      </el-table>
      <!-- 添加分页组件 -->
      <pagination
        v-show="codeTotal>0"
        :total="codeTotal"
        :page.sync="codeQueryParams.pageNum"
        :limit.sync="codeQueryParams.pageSize"
        @pagination="getMachineCodeList"
        style="margin-top: 10px; text-align: right;"
      />
    </el-dialog>
  </div>
</template>

<script>
import { getDeviceType} from "@/api/ma/device";
import { getManufacturerSelect} from "@/api/ma/supplier";
import { getPurchaseDetailsList,getPurchaseFileList,uploadPurchaseFile } from "@/api/purchase/goodsAccept";
import { purchaseWarehouse,getMachineById,rejectPurchaseWarehouse } from "@/api/purchase/goodsEntry";
import { downloadFile } from '@/utils/download'
import { getToken } from '@/utils/auth'
export default {
  name: "EntryDetail",
  dicts: ["purchase_task_status"],
  data() {
    return {
      Id:'',
      taskId:'',
      // 遮罩层
      loading: false,
      dialogLoading: false,
      // 编码入库表格loading
      codeLoading: false,
      isView: false,
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      showHouse: false,
      materialModelList:[],//规格型号下拉
      supplierList:[],//厂家下拉
      ids:[],
      // 总条数
      total: 0,
      //表格数据
      tableList: [],
      fixCodeList:["否","是"],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      rowData:{},
      fileDataList: [
        {dictLabel:"合格证",fileType:"0",name:"",url:""},
        {dictLabel:"型式试验报告",fileType:"1",name:"",url:""},
        {dictLabel:"出厂检测报告",fileType:"2",name:"",url:""},
        {dictLabel:"第三方检测报告",fileType:"3",name:"",url:""},
        {dictLabel:"其他报告",fileType:"4",name:"",url:""},
      ],
      // 查询参数
      queryParams: {
        typeId:undefined,
        supplierId:undefined,
        productionTime:undefined,
      },
      fileListInfo: [],
      fileId: '',
      //图片查看弹窗
      dialogImageUrl: '',
      dialogVisible: false,
      dialogVisibleFile: false,
      //上传
      upload: {
        // 设置上传的请求头部
        headers: { Authorization: 'Bearer ' + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + '/file/upload'
      },
      //编码入库
      openCode:false,
      codeRowData:{},
      codeTableData:[],
      inPutList:[],
      purchaseCheckInfo: null,
      // 编码入库分页参数
      codeQueryParams: {
        pageNum: 1,
        pageSize: 10,
        taskId: '',
        typeId: ''
      },
      // 编码入库总条数
      codeTotal: 0
    };
  },
  mounted() {
    const taskId = this.$route.query && this.$route.query.taskId
    const Id = this.$route.query && this.$route.query.Id
    const isView = this.$route.query && this.$route.query.isView
    this.taskId = taskId;
    this.Id = Id;
    if(isView=='true'){
      this.isView=true;
    }else{
      this.isView=false;
    }
    this.getDeviceType()
    this.getSupplierList()
    console.log(this.isView)
    this.getList()
  },
  methods: {
    // 返回列表页
    jumpList() {
      const obj = { path: '/purchase/goodsEntry' }
      this.$tab.closeOpenPage(obj)
    },
    getDeviceType(){
      getDeviceType({level:4,skipPermission:1}).then(response => {
        let matModelRes = response.data;
        this.materialModelList = matModelRes.map((item) => {
          return {
            label: item.typeName,
            value: item.typeId,
          };
        });
      });
    },
    getSupplierList(){
      getManufacturerSelect().then(response => {
        let arrRes = response.rows;
        this.supplierList = arrRes.map((item) => {
          return {
            label: item.supplier,
            value: item.supplierId,
          };
        });
      });
    },
    /** 查询列表 */
    getList() {
      this.loading = true;
      this.queryParams.id=this.Id
      this.queryParams.taskId=this.taskId
      this.queryParams.taskStage=4
      getPurchaseDetailsList(this.queryParams).then(response => {
        this.tableList = response.data.purchaseCheckDetailsList;
        this.purchaseCheckInfo = response.data.purchaseCheckInfo
        this.tableList.forEach((item) => {
          item.fixCodeStr = this.fixCodeList[Number(item.fixCode)]
        })
        console.log(this.tableList)
        this.loading = false;
      });
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams.keyWord=null;
      this.handleQuery();
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length != 1
      this.multiple = !selection.length
    },
    //入库
    pass(row) {
      if(row.manageType==0){//编码
        this.codeRowData=row
        // 初始化编码分页参数
        this.codeQueryParams = {
          pageNum: 1,
          pageSize: 10,
          taskId: this.taskId,
          typeId: row.typeId
        }
        // 调用分页查询编码列表方法
        this.getMachineCodeList()
      }else{
        const inputNum = Number(row.checkNum) - Number(row.inputNum)
        let obj = {
          taskId: this.taskId,
          typeId:row.typeId,
          purchaseId: row.id,
          typeName: row.maTypeName,
          typeModelName: row.typeName,
          manageType: row.manageType,
          isRs: row.isRs,
          code: this.purchaseCheckInfo.code,
          maCode: row.maCode,
          maTypeName: row.maTypeName,
          unitName: row.unitName,
          inputNum
        };
        console.log('🚀 ~ obj:', obj)
        this.$modal.confirm('是否确认新购入库该物资类型？')
          .then(function() {
            console.log(obj)
            return purchaseWarehouse(obj)
          }).then(() => {
          this.$modal.msgSuccess('入库成功')
          this.getList()
        }).catch(() => {});
      }
    },
    // 获取编码列表（分页版）
    getMachineCodeList() {
      this.codeLoading = true
      // 组合分页查询参数
      let param = {
        ...this.codeQueryParams, // 包含pageNum, pageSize, taskId, typeId
        // 可以添加其他需要的参数
      }
      getMachineById(param).then((res)=>{
        console.log("编码列表分页数据：", res.data)
        // 假设接口返回格式：{data: [], total: 0}
        this.codeTableData = res.data.rows
        this.codeTotal = res.data.total
        this.inPutList = []
        this.openCode = true
        this.codeLoading = false
      }).catch(() => {
        this.codeLoading = false
        this.$modal.msgError('获取编码列表失败')
      })
    },
    //编码勾选
    codeSelection(selection){
      console.log(selection)
      this.inPutList = selection.map(item => {return {'maCode':item.maCode}})
    },
    //编码入库 - 新增加载状态
    codeWarehouse(){
      if(this.inPutList.length>0){
        let obj = {
          taskId: this.taskId,
          typeId: this.codeRowData.typeId,
          purchaseId: this.codeRowData.id,
          inPutList: this.inPutList,
          typeName: this.codeRowData.maTypeName,
          typeModelName: this.codeRowData.typeName,
          manageType: this.codeRowData.manageType,
          isRs: this.codeRowData.isRs,
          code: this.purchaseCheckInfo.code,
          maCode: this.codeRowData.maCode,
          maTypeName: this.codeRowData.maTypeName,
          unitName: this.codeRowData.unitName,
        };
        console.log(obj)
        this.$modal.confirm('是否确认新购入库勾选的编码？')
          .then(() => {
            // 1. 开启全局加载状态
            const loading = this.$loading({text: '提交中...'})

            // 2. 调用入库接口
            return purchaseWarehouse(obj)
              .finally(() => {
                // 3. 无论成功失败，都关闭加载状态
                loading.close()
              })
          }).then(() => {
          this.openCode = false
          this.getList()
          this.$modal.msgSuccess('入库成功')
        }).catch(() => {
          this.$modal.msgError('入库失败，请重试')
        });
      } else {
        this.$modal.msgError('请先勾选入库编码！')
      }
    },
    //驳回
    reject(row) {
      let obj = {
        taskId: this.taskId,
        typeId: row.typeId,
        purchaseId: row.id
      };
      this.$modal.confirm('是否确认驳回该物资类型？')
        .then(function () {
          console.log(obj)
          return rejectPurchaseWarehouse(obj)
        }).then(() => {
        this.$modal.msgSuccess('驳回成功')
        this.getList()
      }).catch(() => {
      });
    },
    //文件管理
    async openFileDialog(row) {
      this.rowData = row;
      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: []}
      ]
      if (this.rowData.bmFileInfos == null) {
        await this.getFileData()
        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 => {
          if (response.rows.length > 0) {
            response.rows.forEach(item => {
              let index = this.fileDataList.findIndex(v => v.fileType == item.fileType)
              item.fileDetailList.forEach(item2 => {
                const obj = {
                  taskId: this.taskId,
                  taskType: '0',
                  name: item2.name,
                  url: item2.url,
                  modelId: this.rowData.partId,
                  fileType: item2.fileType
                }
                this.rowData.bmFileInfos.push(obj)
                console.log('77777777', this.rowData)
              })
            })
          }
        })
        .catch(() => {
        })
    },
    beforeFileUpload(row) {
      this.rowData.fileType = row.fileType;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      if (response.code == 200) {
        let param = {
          "taskId": this.taskId,
          "taskType": "0",
          "name": response.data.name,
          "url": response.data.url,
          "modelId": this.rowData.typeId,
          "fileType": this.rowData.fileType,
        }
        console.log(param)
        uploadPurchaseFile(param).then((response) => {
          this.$modal.msgSuccess('上传成功')
          this.getFileData()
        }).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
      }
    },
    /** 导出按钮操作 */
    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/purchase_check_info/exportDetails",
        {taskId: this.taskId, taskStage: 4, id: this.Id},
        `新购入库详情_${currentTime}.xlsx`
      );
    },
  }
};
</script>
<style lang="scss" scoped>
.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;
}

//隐藏图片上传框的css
::v-deep.disabled {
  .el-upload--picture-card {
    display: none;
  }
}
</style>
