<template>
  <div class="app-container" id="acceptDetail">
    <el-row :gutter="20">
      <el-col :span="19" :offset="0">
        <el-form
          :model="queryParams"
          ref="queryForm"
          size="small"
          :inline="true"
          v-show="showSearch"
          label-width="90px"
        >
          <el-form-item label="类型规格：" prop="partId">
            <el-select
              v-model="queryParams.partId"
              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"
              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-col :span="1.5">
            <el-button
              type="success"
              @click="batchPass"
              icon="el-icon-check"
              v-show="!isView"
              size="mini"
              >合格</el-button
            >
          </el-col>
    
          <el-col :span="1.5">
            <el-button
              type="danger"
              @click="batchReject"
              icon="el-icon-close"
              v-show="!isView"
              size="mini"
              >不合格</el-button
            >
          </el-col>
        </el-row>
    
        <el-table
          v-loading="loading"
          :data="tableList"
          ref="multipleTable"
        >
          <!-- <el-table-column
            type="selection"
            width="55"
            align="center" :selectable="selectable"
            :reserve-selection="true"
          /> -->
          <el-table-column label="序号" align="center" width="80" type="index">
          </el-table-column>
          <el-table-column
            label="配件类型"
            align="center"
            prop="maName"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            label="配件名称"
            align="center"
            prop="maTypeName"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            label="规格型号"
            align="center"
            prop="partName"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            label="到货数量"
            align="center"
            prop="purchaseNum"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            label="单位"
            align="center"
            prop="unitName"
            :show-overflow-tooltip="true"
          />
    
          <!-- <el-table-column
            label="供应商"
            align="center"
            prop="supplier"
            :show-overflow-tooltip="true"
          /> -->
          <el-table-column
            label="出厂日期"
            align="center"
            prop="productionTime"
            :show-overflow-tooltip="true"
          />
          <el-table-column
                label="相关配套资料"
                align="center"
                prop=""
            >
          <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="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==0">
                入库
              </el-button>
              <el-button size="mini" type="danger" @click="reject(scope.row)" v-if="scope.row.status==0">
                驳回
              </el-button>
            </template>
          </el-table-column> -->
        </el-table>
      </el-col>
      <el-col :span="5" :offset="0">
        <div class="right-container">
          <div class="right-title">
            <div></div>
            <div></div>
            <div>流程记录</div>
          </div>

          <div class="process-record">
            <el-steps :space="120" direction="vertical">
              <el-step v-for="(step, index) in auditingList" :key="index" :title="step.deptName">
                <template slot="description">
                  <div class="custom-description">
                    审核结果:
                    <el-tag size="mini" type="primary" v-if="step.auditStatus == 0">待审核</el-tag>
                    <el-tag size="mini" type="success" v-if="step.auditStatus == 1">审核通过</el-tag>
                    <el-tag size="mini" type="danger" v-if="step.auditStatus == 2">审核驳回</el-tag>
                  </div>

                  <div class="node-info" v-if="step.userName">
                    审核人:
                    {{ step.userName }}
                  </div>

                  <div class="node-info" v-if="step.createTime">
                    审核时间:
                    {{ step.createTime }}
                  </div>

                  <div class="node-info" v-if="step.auditRemark">
                    审核意见:
                    {{ step.auditRemark }}
                  </div>
                </template>
              </el-step>
            </el-steps>
          </div>
        </div>
      </el-col>
    </el-row>

    <!-- 验收弹窗 -->
    <el-dialog title="验收" :visible.sync="confirmShow" width="600px" height="300px">
      <div style="width: 100%; height: 80%; display: flex;margin-bottom: 10px;">
        <div style="width:15%;">验收结论：</div>
        <el-input
          type="textarea"
          :rows="3" style="width:80%;"
          placeholder="请输入结论"
          v-model="checkResult"
          maxlength="100">
        </el-input>
      </div>
      <div style="width: 100%;height: 20%;display: flex;justify-content: flex-end;align-items: center;">
        <el-button type="primary" @click="confirmCheck">确认</el-button>
        <el-button size="mini" @click="confirmShow = false">取消</el-button>
      </div>
    </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.partName}}</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"
                    :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.fileListTemp!=0">
                        查看
                    </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>
  </div>
</template>

  <script>
import { getManufacturerSelect } from "@/api/ma/supplier";
import {
  acceptInnerVerifyer,
  getPurchaseFileList,
  uploadPurchaseFile,
  } from "@/api/purchase/goodsAccept";
import { getPartType,partTypeWarehouse,partTypeReject,innerVerify } from '@/api/part/partAccept';
import { getPartTypeCheckInfo,getPartTypeFileList } from '@/api/part/partArrived';
import { downloadFile } from "@/utils/download";
import { getToken } from "@/utils/auth";
import { getSignListApi } from '@/api/purchase/goodsAccept'
export default {
  name: "PartAcceptDetailTwo",
  dicts: ["purchase_task_status"],
  data() {
    return {
      Id: "",
      taskId: "",
      // 遮罩层
      loading: false,
      dialogLoading: false,
      isView: false,
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      showHouse: false,
      materialModelList: [], //规格型号下拉
      supplierList: [], //厂家下拉
      ids: [],
      infos: [],
      checkList: [],
      // 总条数
      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,
        partId: undefined,
        supplierId: undefined,
        productionTime: undefined,
      },
      //确认弹窗
      confirmShow: false,
      taskStatus: "", //3合格、1不合格
      checkResult: "",
      verifyPass: true, //true合格、false不合格
      //图片查看弹窗
      dialogImageUrl: "",
      dialogVisible: false,
      //上传
      upload: {
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/file/upload",
      },
      fileListInfo:[],
      dialogVisibleFile: false,
      auditingList: []
    };
  },
  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.getPartType();
    console.log(this.isView);
    this.getList();
    this.getSignList()
  },
  methods: {
    // 流程图
    async getSignList() {
      try {
        const res = await getSignListApi({ taskId: this.taskId })
        console.log('🚀 ~ getSignList ~ res:', res)
        // 合并auditingList
        if (res.code === 200 && res.data && res.data.length > 0) {
          const kuGuanOrder = ['库管一班', '库管二班', '库管三班']
          // 用 deptName 去重
          const map = new Map()
          res.data.forEach(item => map.set(item.deptName, { ...item }))
          // 查找有数据的库管班
          const kuGuanItem = kuGuanOrder.map(name => map.get(name)).find(Boolean)
          // 组装最终列表
          this.auditingList = [
            // 第一层：供应科，userName 没有值时默认 '姚士超'
            (() => {
              const item = map.get('供应科') || { deptName: '供应科', auditStatus: 1 }
              return { ...item, userName: item.userName || '姚士超' }
            })(),
            // 第二层：技术科
            map.get('技术科') || { deptName: '技术科', auditStatus: 0 },
            // 第三层：库管班
            kuGuanItem || { deptName: '库管班', auditStatus: 0 }
          ]
          console.log('🚀 ~ getSignList ~ this.auditingList:', this.auditingList)
        }
      } catch (error) {
        console.log('🚀 ~ getSignList ~ error:', error)
      }
    },
    //是否可用勾选框
    selectable(row) {
      console.log(row)
      if (row.status == 2||row.status == 13 ||row.status == 14) {
          return true
      } else {
          return false
      }
    },
    // 返回列表页
    jumpList() {
      const obj = { path: "/part/partAcceptTwo" };
      this.$tab.closeOpenPage(obj);
    },
    getPartType() {
      getPartType({ level: 3 }).then((response) => {
        let matModelRes = response.data;
        this.materialModelList = matModelRes.map((item) => {
          return {
            label: item.partName,
            value: item.partId,
          };
        });
      });
    },
    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;
      getPartTypeCheckInfo(this.queryParams).then((response) => {
        this.tableList = response.data.partTypeCheckDetailsList;
        // 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;
      this.infos = [];
      selection.forEach((item) => {
        this.infos.push({id:item.id,partId:item.partId,purchaseNum:item.purchaseNum,taskId:item.taskId});
      });
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    //入库
    pass(row) {
      // if(this.infos==0){
      //   this.$modal.msgError("请选择配件");
      //   return;
      // }

      const infos=[{id:row.id,partId:row.partId,purchaseNum:row.purchaseNum,taskId:this.taskId}]
      this.$modal.confirm('是否确认入库该配件？')
            .then(function() {
              return partTypeWarehouse(infos)
            }).then(() => {
                  this.$modal.msgSuccess('入库成功')
                  this.getList()
            }).catch(() => {});
    },
    //驳回
    reject(row) {
      const infos=[{id:row.id,partId:row.partId,purchaseNum:row.purchaseNum,taskId:this.taskId}]
      this.$modal.confirm('是否确认驳回该配件？')
            .then(function() {
              return partTypeReject(infos)
            }).then(() => {
                  this.$modal.msgSuccess('驳回成功')
                  this.getList()
            }).catch(() => {});
    },

    //批量入库
    batchPass() {
      // if(this.infos==0){
      //   this.$modal.msgError("请选择配件");
      //   return;
      // }
      this.taskStatus = "3";
      this.checkResult = "合格";
      this.verifyPass = true;
      this.checkList = [];
      this.checkList = this.tableList.map((item) => {
        let obj = {
          taskId: item.taskId,
          partId: item.partId,
          checkResult: this.checkResult,
        };
        return obj;
      });
      this.confirmShow = true;
    },

    //批量驳回
    batchReject() {
    //  if(this.infos==0){
    //     this.$modal.msgError("请选择配件");
    //     return;
    //   }
      this.taskStatus = "1";
      this.checkResult = "不合格";
      this.verifyPass = false;
      this.checkList = [];
      this.checkList = this.tableList.map((item) => {
        let obj = {
          taskId: item.taskId,
          partId: item.partId,
          checkResult: this.checkResult,
        };
        return obj;
      });
      this.confirmShow = true;
    },

    //验收确认请求
    confirmCheck() {
      this.checkList.forEach((item) => {
        item.checkResult = this.checkResult;
      });
      let param = {
        purchaseCheckDetailsList:this.checkList,
        verifyPass:this.verifyPass
      }
      console.log(param);
      innerVerify(param).then((response) => {
        if (response.code == 200) {
          this.$modal.msgSuccess("验收成功");
          this.confirmShow = false;
          this.getList();
          this.$refs.multipleTable.clearSelection();
          // 返回
          this.jumpList()
        }
      });
    },
      //文件管理
      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:[]}]
        this.getFileData()
        this.open=true
      },
      getFileData(){
        let param = {
          modelId:this.rowData.partId,
          taskType:13,
          taskId:this.rowData.taskId
        }
        getPartTypeFileList(param).then((response) => {
          if(response.data.length>0){
              response.data.forEach(item=>{
                  let index = this.fileDataList.findIndex(v => v.fileType == item.fileType)
                  item.fileDetailList.forEach(item2=>{
                      this.fileDataList[index].fileList.push({
                          name:item2.name,
                          url:item2.url
                      })
                      this.fileDataList[index].fileListTemp.push({
                          name:item2.name,
                          url:item2.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("上传失败");
          });
      }
    },
    picturePreviewFile(row) {
          this.fileListInfo = row.fileListTemp

          this.dialogVisibleFile = true
      },
    //图片查看
    picturePreview(file) {
      this.dialogImageUrl = file.url;
      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/part_arrived/exportDetails",
        { taskId: this.taskId },
        `新购到货详情_${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;
  }
}
.right-container {
  padding: 0 20px;
  .right-title {
    display: flex;
    align-items: center;
    font-size: 14px;
    & div:first-child {
      width: 16px;
      height: 16px;
      border-radius: 50%;
      background-color: #19a4a0;
      z-index: 9;
    }
    & div:nth-child(2) {
      width: 16px;
      height: 16px;
      border-radius: 50%;
      background-color: #b2e1e0;
      transform: translateX(-50%);
    }
  }
  .process-record {
    margin-top: 20px;
    //   height: 60vh;
    .node-info {
      word-break: break-all;
      white-space: pre-wrap;
    }
  }
}


.btn-container {
  margin-top: 10px;
  display: flex;
  justify-content: space-around;
}

::v-deep .el-step__icon.is-text {
  background-color: #19a4a0;
  color: #19a4a0;
  border: none;
  width: 16px;
  height: 16px;
}

::v-deep .el-step.is-vertical .el-step__line {
  width: 2px;
  top: 26px;
  bottom: 8px;
  left: 7px;
}

::v-deep .el-step__title.is-finish {
  font-weight: bold;
  color: #303133;
  font-size: 16px;
}

::v-deep .el-step__title.is-wait {
  font-weight: bold;
  color: #303133;
  font-size: 16px;
}
// 居中
.cont-center {
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
