<template>
  <div class="app-container">
    <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>
          <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="supplierId">
        <el-select v-model="queryParams.supplierId" placeholder="请选择机具厂家" clearable>
          <el-option
            v-for="dict in supplierList"
            :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 HH:mm:ss"
              type="datetime">
          </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="success" 
                  icon="el-icon-check" v-show="!isView"
                  size="mini" :disabled="multiple"
              >入库</el-button>
          </el-col>

          <el-col :span="1.5">
              <el-button
                  type="danger" 
                  icon="el-icon-close" v-show="!isView"
                  size="mini" :disabled="multiple"
              >驳回</el-button>
          </el-col> -->
      </el-row>

    <el-table v-loading="loading" :data="tableList" ref="multipleTable" row-key="teamId" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" :reserve-selection="true" v-if="!isView"/>
      <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="purchaseTaxPrice" :show-overflow-tooltip="true"/>
      <el-table-column label="购置单价（元不含税）" align="center" prop="purchasePrice" :show-overflow-tooltip="true"/>
      <!-- <el-table-column label="供应商" align="center" prop="supplierName" /> -->
      <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="" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <div style="color: rgb(2, 167, 240);cursor: pointer;" @click="openFileDialog(scope.row)">报告管理</div>
        </template>
      </el-table-column>
      <el-table-column label="验收结论" align="center" prop="checkResult" :show-overflow-tooltip="true"/>
      <el-table-column label="操作" align="center" width="180">
          <template slot-scope="scope">
              <el-button size="mini" type="success" @click="pass(scope.row)">
                入库
              </el-button>
              <!-- <el-button size="mini" type="danger" @click="reject(scope.row)">
                驳回
              </el-button> -->
          </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="报告管理" :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" 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: center;">
              <el-upload ref="upload" :limit="1" :headers="upload.headers" v-show="!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="picturePreview(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>


  </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 } from "@/api/purchase/goodsEntry";
import { downloadFile } from '@/utils/download'
import { getToken } from '@/utils/auth'
export default {
  name: "GoodsAcceptDetail",
  data() {
    return {
      Id:'',
      taskId:'',
      // 遮罩层
      loading: false,     
      dialogLoading: 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: {
        // pageNum: 1,
        // pageSize: 10,
        typeId:undefined,
        supplierId:undefined,
        productionTime:undefined,
      },
       //图片查看弹窗
      dialogImageUrl: '',
      dialogVisible: false,
      //上传
      upload: {
        // 设置上传的请求头部
        headers: { Authorization: 'Bearer ' + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + '/file/upload'
      },
    };
  },
  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.statusList=[4,14,19]
          getPurchaseDetailsList(this.queryParams).then(response => {
              this.tableList = response.data.purchaseCheckDetailsList;
              this.tableList.forEach((item) => {
                  item.fixCodeStr = this.fixCodeList[Number(item.fixCode)]
              })
              // this.total = response.total;
              this.loading = false;
          });
      },
      /** 重置按钮操作 */
      resetQuery() {
          this.resetForm("queryForm");
          this.queryParams.keyWord=null;
          this.handleQuery();
      },
      /** 搜索按钮操作 */
      handleQuery() {
          this.queryParams.pageNum = 1;
          this.getList();
      }, 
      // 多选框选中数据
      handleSelectionChange(selection) {
          this.ids = selection.map(item => item.id)
          this.single = selection.length != 1
          this.multiple = !selection.length
      },
      //入库
      pass(row) { 
        let obj = {
          // taskId: this.taskId,
          purchaseId: row.id
        };
        console.log(obj)  
        purchaseWarehouse(obj).then((res)=>{
            console.log(res)
            if(res.code==200){
              this.$modal.msgSuccess('操作成功')
              this.getList()
            }
        })
      },
      //不合格
      reject(row) {
         
      },

      //文件管理
      openFileDialog(row){
        this.rowData=row;
        this.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:""}]
        this.getFileData()
        this.open=true
      },
      getFileData(){
        let param = {
          modelId:this.rowData.typeId,
          taskType:0,
          taskId:this.rowData.taskId
        }
        getPurchaseFileList(param).then((response) => {
          if(response.rows.length>0){
              response.rows.forEach(item=>{
                  let index = this.fileDataList.findIndex(v=>v.fileType==item.fileType)
                  this.fileDataList[index].name = item.name
                  this.fileDataList[index].url = item.url
              })
          }
          }).catch(() => {
          })
      },
      beforeFileUpload(row){
        this.rowData.fileType=row.fileType;
        // this.rowData.dictLabel=row.dictLabel;
      },
      // 文件上传成功处理
      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('上传失败')
          })
        }
      },
      //图片查看
      picturePreview(file) {
        this.dialogImageUrl = file.url;
        const parts = file.name.split('.');
        const extension = parts.pop();
        if(extension === 'doc'||extension === 'docx'||extension === 'pdf'){
          const windowName = file.name;
          window.open(file.url,windowName)
        }else{
          this.dialogVisible = true
        }
      },


  }
};
</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>