<template>
  <div class="app-container check-detection-drawer">
    <el-drawer v-if="onOpen" :visible.sync="onOpen" direction="rtl" size="60%" style="padding-left: 20px">
      <template slot="title">
        <div>{{ drawerTitle + " 【材料取样复试】" }}</div>
      </template>
      <el-tabs type="card" v-model="unitActiveName" style="margin-left: 20px; margin-right: 20px" @tab-click="getList">
        <el-tab-pane v-for="(it, idx) in nodes" :label="it.unitName + ''" :name="it.unitId + ''"
          :key="idx"></el-tab-pane>
      </el-tabs>
      <el-row :gutter="10" class="mb8" style="margin-left: 25px; margin-top: 10px; margin-right: 0px" v-if="canCreated">
        <el-col :span="1.5">
          <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
            v-hasPermi="['project:checkDetection:add']">添加</el-button>
        </el-col>
        <!-- <el-col :span="1.5">
          <el-button
            type="success"
            plain
            icon="el-icon-edit"
            size="mini"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['project:checkDetection:edit']"
            >修改</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['project:checkDetection:remove']"
            >删除</el-button
          >
        </el-col> -->
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>
      <el-tabs type="card" v-model="queryParams.activeName" @tab-click="getList" style="margin-left: 25px; margin-right: 25px">
        <el-tab-pane :label="tabs.all" name="all"></el-tab-pane>
        <el-tab-pane :label="tabs.jxz" name="jxz"></el-tab-pane>
        <el-tab-pane :label="tabs.ywc" name="ywc"></el-tab-pane>
        <el-table v-loading="loading" :data="checkDetectionList" @selection-change="handleSelectionChange" stripe>
          <el-table-column label="送检类型" align="center" prop="checkType">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.check_detection_check_type" :value="scope.row.checkType" />
            </template>
          </el-table-column>
          <el-table-column label="材料名称" align="center" prop="materialName" width="120">
            <template slot-scope="scope">
              <div>{{ scope.row.materialName }}</div>
              <div>{{ scope.row.usePosition }}</div>
            </template>
          </el-table-column>
          <el-table-column label="取样数量" align="center" prop="sampleNum" width="80" show-overflow-tooltip />
          <el-table-column label="合格证" align="center" prop="qualifiedFlag">
            <template slot-scope="scope">
              <el-tag v-if="scope.row.qualifiedFlag == 'Y'" type="success">已提供</el-tag>
              <el-tag v-if="scope.row.qualifiedFlag == 'N'" type="danger">未提供</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="监理专员" align="left" prop="witnessUser" width="120" show-overflow-tooltip>
            <template slot-scope="scope">
              <div>{{ scope.row.witnessUserName }}</div>
              <div>{{ scope.row.witnessUser }}</div>
            </template>
          </el-table-column>
          <el-table-column label="送检时间" align="center" prop="checkTime" width="100">
            <template slot-scope="scope">
              <div>{{ parseTime(scope.row.checkTime, "{y}-{m}-{d}") }}</div>
              <div>{{ scope.row.laboratoryName }}</div>
            </template>
          </el-table-column>
          <!-- <el-table-column label="检测结果" align="center" prop="detectionResult">
            <template slot-scope="scope">
              <dict-tag
                :options="dict.type.project_checking_result"
                :value="scope.row.detectionResult"
              />
            </template>
          </el-table-column> -->
          <el-table-column label="审批状态" align="center" prop="approveStatus" width="120">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.project_check_status" :value="scope.row.approveStatus" />
            </template>
          </el-table-column>
          <el-table-column label="提交时间" align="center" prop="createTime" width="100">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
          <el-table-column label="操作" align="center" width="180" fixed="right" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button v-if="scope.row.checkState == '2'" size="mini" type="text" icon="el-icon-paperclip"
                @click="handleDownload(scope.row)" v-hasPermi="['project:surProjectSpecial:list']">下载检测报告</el-button>
              <el-button v-if="scope.row.approveStatus != '4'" size="mini" type="text" icon="el-icon-edit-outline"
                @click="handleUpdateResult(scope.row)" style="margin-left: 8px"
                v-hasPermi="['project:checkDetection:editResult']">登记检测结果</el-button>
              <el-button v-if="scope.row.approveStatus != null" size="mini" type="text" icon="el-icon-tickets"
                @click="handleAuditinfo(scope.row)">审批日志</el-button>
              <el-button v-if="scope.row.approveStatus != '4'" size="mini" type="text" icon="el-icon-edit"
                @click="handleUpdate(scope.row)" v-hasPermi="['project:checkDetection:edit']">修改</el-button>
              <el-button v-if="scope.row.approveStatus != '4'" size="mini" type="text" icon="el-icon-delete"
                @click="handleDelete(scope.row)" v-hasPermi="['project:checkDetection:remove']">删除</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-tabs>
      <el-dialog :title="title" v-if="open" :visible.sync="open" width="900px" append-to-body  custom-class="prj-checking-detection-drawer-dlg"
        :close-on-click-modal="false" :close-on-press-escape="false">
        <el-form ref="form" :model="form" :rules="rules" label-width="120px">
          <el-row>
            <el-col :span="12">
              <el-form-item label="项目名称" prop="projectName">
            <el-input v-model="form.projectName" placeholder="请输入项目名称" :disabled="true" />
          </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="单位名称" prop="deptName">
            <el-input v-model="form.deptName" placeholder="请输入单位名称" :disabled="true" />
          </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="24">
              <el-form-item label="送检类型" prop="checkType">
            <el-select v-model="form.checkType" placeholder="请选择送检类型" style="width: 100%">
              <el-option v-for="dict in dict.type.check_detection_check_type" :key="dict.value" :label="dict.label"
                :value="dict.value"></el-option>
            </el-select>
          </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="24">
              <el-form-item label="材料名称" prop="materialName">
            <el-input v-model="form.materialName" placeholder="请输入材料名称" />
          </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="24">
              <el-form-item label="使用部位" prop="usePosition">
            <el-input v-model="form.usePosition" placeholder="请输入使用部位" />
          </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="24">
              <el-form-item label="取样数量" prop="sampleNum">
            <el-input v-model="form.sampleNum" placeholder="请输入取样数量" />
          </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="12">
              <el-form-item label="提供合格证" prop="qualifiedFlag">
            <el-select v-model="form.qualifiedFlag" placeholder="请选择提供合格证" style="width: 100%">
              <el-option v-for="dict in dict.type.sys_yes_no" :key="dict.value" :label="dict.label"
                :value="dict.value"></el-option>
            </el-select>
          </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="监理专员" prop="witnessUser">
            <el-select v-model="form.witnessUser" placeholder="请选择监理专员" filterable style="width: 100%"
              @change="selectWitnessUser">
              <el-option-group v-for="group in deptUserData" :key="group.unitId + ''"
                :label="group.unitName + ' [' + group.unitTypeName + '] '">
                <el-option v-for="(item, index) in group.userinfoList" :key="index"
                  :label="item.nickName + ' [' + item.jobTypeName + '] '" :value="item.phonenumber">
                </el-option>
              </el-option-group>
            </el-select>
          </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="24">
              <el-form-item label="实验室名称" prop="laboratoryName">
            <el-input v-model="form.laboratoryName" placeholder="请输入实验室名称" />
          </el-form-item>
            </el-col>
          </el-row>

          <el-row>
          <el-col :span="12">
            <el-form-item label="委托单" prop="trustDeed" :class="form.trustDeed?'img-1':''">
              <image-upload v-model="form.trustDeed" :limit="1" />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="false">
            <el-form-item label="样品照片" prop="specimenPhoto" :class="form.specimenPhoto?'img-1':''">
              <image-upload v-model="form.specimenPhoto" :limit="1" />
            </el-form-item>
          </el-col>
        </el-row>

          <el-row>
            <el-col :span="24">
              <el-form-item label="送检时间" prop="checkTime">
            <el-date-picker clearable v-model="form.checkTime" type="date" value-format="yyyy-MM-dd"
              placeholder="请选择送检时间">
            </el-date-picker>
          </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="24">
              <el-form-item label="附件" prop="attachmentFiles" class="mg-b-8">
              <FileUpload :limit="10" v-model="form.attachmentFiles" />
            </el-form-item>
            </el-col>
          </el-row>
          
        </el-form>
        <div slot="footer" class="dialog-footer" style="text-align: center;">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-dialog>

      <!-- 材料取样复试等级结果 -->
      <el-dialog :title="title" v-if="resultopen" :visible.sync="resultopen" width="680px" append-to-body
        :close-on-click-modal="false" :close-on-press-escape="false">
        <el-form ref="resultform" :model="resultform" :rules="resultrules" label-width="100px">
          <el-form-item label="项目名称">
            <el-input v-model="resultform.projectName" placeholder="请输入项目名称" :disabled="true" />
          </el-form-item>
          <el-form-item label="单位名称">
            <el-input v-model="resultform.deptName" placeholder="请输入单位名称" :disabled="true" />
          </el-form-item>
          <el-form-item label="送检类型">
            <el-select v-model="resultform.checkType" placeholder="请选择送检类型" style="width: 100%" :disabled="true">
              <el-option v-for="dict in dict.type.check_detection_check_type" :key="dict.value" :label="dict.label"
                :value="dict.value"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="材料名称">
            <el-input v-model="resultform.materialName" placeholder="请输入材料名称" :disabled="true" />
          </el-form-item>
          <el-form-item label="实验室名称">
            <el-input v-model="resultform.laboratoryName" placeholder="请输入实验室名称" :disabled="true" />
          </el-form-item>
          <el-form-item label="送检时间">
            <el-input v-model="resultform.checkTime" placeholder="请输入实送检时间" :disabled="true" />
          </el-form-item>
          <el-form-item label="检测结果" prop="detectionResult" v-if="false">
            <el-radio v-model="resultform.detectionResult" v-for="dict in dict.type.project_checking_result"
              :label="dict.value" :key="dict.value" border size="small">{{ dict.label }}</el-radio>
          </el-form-item>
          <el-form-item label="检测报告" prop="detectionFile">
            <FileUpload v-model="resultform.detectionFile" :limit="2" @input="fileInput"
              :fileType="['pdf', 'png', 'jpg', 'jpeg']" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitResultForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-dialog>
    </el-drawer>
    <indexDrawer ref="indexDrawer" />
  </div>
</template>

<script>
import {
  listCheckDetection,
  getCheckDetection,
  delCheckDetection,
  addCheckDetection,
  updateCheckDetection,
  findGroupCountByApprove,
  updateCheckDetectionResult,
} from "@/api/project/checkDetection";
import indexDrawer from "../projectAuditinfo/indexDrawer.vue";

export default {
  components: {
    indexDrawer,
  },
  props: {},
  dicts: ["sys_yes_no", "project_check_status", "project_checking_result", "check_detection_check_type"],
  data() {
    return {
      canCreated:true,
      showViewer: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 总条数
      total: 0,
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 是否显示弹出层
      open: false,
      resultopen: false,
      // 弹出层标题
      title: "",
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        projectId: null,
        deptId: null,
        activeName: "jxz",
      },
      // 表单参数
      form: {},
      resultform: {},
      // 表单校验
      rules: {
        checkType: [{ required: true, message: "请选择送检类型", trigger: "blur" }],
        materialName: [
          { required: true, message: "请输入送检材料名称", trigger: "blur" },
          { max: 100, message: "送检材料名称最多100字符", trigger: "blur" },
        ],
        usePosition: [
          { required: true, message: "请输入使用部位", trigger: "blur" },
          { max: 100, message: "使用部位最多100字符", trigger: "blur" },
        ],
        usePosition: [
          { required: true, message: "请输入使用部位", trigger: "blur" },
          { max: 100, message: "使用部位最多100字符", trigger: "blur" },
        ],
        sampleNum: [
          { required: true, message: "请输入取样数量", trigger: "blur" },
          { max: 100, message: "取样数量最多100字符", trigger: "blur" },
        ],
        qualifiedFlag: [
          { required: true, message: "请选择是否提供合格证", trigger: "blur" },
        ],
        trustDeed:[
          {required:true,message:'请上传委托单',trigger:"blur"}
        ],
        specimenPhoto:[
          {required:true,message:'请上传样品照片',trigger:"blur"}
        ],
        witnessUser: [
          { required: true, message: "请选择监理单位监理专员", trigger: "blur" },
        ],
        laboratoryName: [
          { required: true, message: "请输入实验室名称", trigger: "blur" },
          { max: 100, message: "实验室名称最多100字符", trigger: "blur" },
        ],
        checkTime: [{ required: true, message: "请选择送检时间", trigger: "blur" }],
      },
      resultrules: {
        detectionResult: [{ required: false, message: "请选择检测结果", trigger: "blur" }],
        detectionFile: [{ required: true, message: "请上传检测报告", trigger: "blur" }],
      },
      deptUserData: [],
      tabs: {
        all: "全部数据（0）",
        jxz: "进行中（0）",
        ywc: "已完成（0）",
      },
      checkDetectionList: [],
      project: null,
      nodes: [],
      unitActiveName: "",
      onOpen: false,
      drawerTitle: "",
    };
  },
  computed: {},
  watch: {},
  created() { },
  mounted() { },
  beforeDestroy() { },
  methods: {
    fileInput(files) {
      let fileUrls = "";
      if (files.length > 0) {
        fileUrls = "";
        files.forEach((item) => {
          fileUrls += "," + item.url;
        });
        fileUrls = fileUrls.substring(1);
      }
      this.resultform.detectionFile = fileUrls;
    },
    show(project) {
      this.project = project;
      this.drawerTitle = project.projectName;
      this.onOpen = true;
      this.queryParams.projectId = project.id;
      this.tabs.all = "全部数据（0）";
      this.tabs.jxz = "进行中（0）";
      this.tabs.ywc = "已完成（0）";
      this.$api.publics
        .queryUnitList({
          projectId: project.id,
          unitTypes: [2,4]
        })
        .then((d) => {
          this.nodes = d.rows;
          if (d.rows.length > 0) {
            this.unitActiveName = this.nodes[0].unitId + "";
            this.getList();
          } else {
            this.checkDetectionList = [];
          }
        });
    },
    /** 查询特种人员列表 */
    getList() {
      let tmps=this.nodes.filter(d=>d.unitId==this.unitActiveName);
      this.canCreated=tmps.length>0  && tmps[0].unitType==4?false:true;
      this.loading = true;
      this.queryParams.deptId = this.unitActiveName;
      this.queryCount();
      listCheckDetection(this.queryParams).then((response) => {
        this.checkDetectionList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    queryCount() {
      findGroupCountByApprove(this.queryParams).then((response) => {
        if (response && response.data) {
          this.tabs.jxz = "进行中（" + response.data.jxz + "）";
          this.tabs.ywc = "已完成（" + response.data.ywc + "）";
          this.tabs.all = "全部数据（" + (response.data.jxz + response.data.ywc) + "）";
        }
      });
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        projectId: null,
        deptId: null,
        name: null,
        sex: null,
        age: null,
        phoneNumber: null,
        idNumber: null,
        isCredential: null,
        credentialNumber: null,
        credentialExpirationTime: null,
        credentialFile: null,
        isDel: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
        credentialType: null,
        specialType: null,
      };
      this.files = [];
      this.resetForm("form");
    },
    getDeptName(){
      let tmps=this.nodes.filter(d=>d.deptId==+this.unitActiveName);
      return tmps.length>0?tmps[0].deptName:"";
    },
    /** 新增按钮操作 */
    handleAdd() {
      debugger
      this.reset();
      this.credential = false;
      this.form.projectId = this.project.id;
      this.form.projectName = this.project.projectName;
      this.form.deptId = this.unitActiveName;
      this.form.deptName=this.getDeptName();
      this.open = true;
      this.title = "添加材料取样复试";
      //查询单位人员
      this.$api.publics
        .selectProjectUnitUser({
          unitType: "4",
          projectId: this.project.id,
        })
        .then((d) => {
          this.deptUserData = d.data;
        });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.resultopen = false;
      this.reset();
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getCheckDetection(id).then((response) => {
        let obj= response.data;
        obj.attachmentFiles=this.$tryToJson(obj.attachment||'[]',[]).map(d=>{
          return {
            name:d,
            url:d
          }
        });
        this.form = obj;
        this.files = this.form.credentialFile;
        this.open = true;
        this.title = "修改材料取样复试";
      });
      //查询单位人员
      this.$api.publics
        .selectProjectUnitUser({
          unitType: "4",
          projectId: this.project.id,
        })
        .then((d) => {
          this.deptUserData = d.data;
        });
    },
    /** 登记结果按钮操作 */
    handleUpdateResult(row) {
      this.reset();
      getCheckDetection(row.id).then((response) => {
        this.resultform = response.data;
        this.resultopen = true;
        this.title = "取样复试登记检测结果";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.form.attachment=this.form.attachmentFiles?JSON.stringify(this.form.attachmentFiles.map(d=>d.url)):"[]";
          if (this.form.id) {
            //已经上传过检测结果时，修改重新发起提交申请
            if (this.form.checkState == "2") {
              this.resultform.approveStatus = "1";
            }
            updateCheckDetection(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addCheckDetection(this.form).then((response) => {
              this.$modal.msgSuccess("添加成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 登记取样复试结果 */
    submitResultForm() {
      this.$refs["resultform"].validate((valid) => {
        if (valid) {
          // 修改取样复试检测结果
          this.resultform.checkState = "2";
          this.resultform.approveStatus = "1";
          updateCheckDetectionResult(this.resultform).then((response) => {
            this.$modal.msgSuccess("登记结果成功");
            this.resultopen = false;
            this.getList();
          });
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除特种人员编号为"' + ids + '"的数据项？')
        .then(function () {
          return delCheckDetection(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => { });
    },
    /** 选择监理专员*/
    selectWitnessUser(val) {
      this.deptUserData.forEach((item) => {
        item.userinfoList.forEach((u) => {
          if (u.phonenumber == val) {
            this.form.witnessUserName = u.nickName + " [" + u.jobTypeName + "] ";
          }
        });
      });
    },
    /** 下载附件 */
    handleDownload(row) {
      this.files = row.detectionFile.split(",");
      this.files.forEach((item) => {
        this.$download.resource(item);
      });
    },
    /** 审批日志 */
    handleAuditinfo(row) {
      row.title = "材料取样复试";
      row.logType = "1";
      this.$refs.indexDrawer.show(row);
    }
  },
};
</script>
<style lang="scss">
.prj-checking-detection-drawer-dlg{
  .el-dialog__body{
    padding:0px 10px;
    
    .el-form-item{
      margin-bottom: 16px;      
      &.mg-b-8{
        margin-bottom: 8px;
      }
      &.img-1{
        .el-upload--picture-card{
          display: none;
        }
        .el-upload__tip{
          display: none;
        }
      }
      .upload-file {
        .upload-file-uploader{
          display: flex;
          align-items: center;
          margin-bottom: 0px;
          line-height: 30px;
          .el-upload__tip{
            margin-left: 8px;
          }
        }
      }
      .el-form-item__error{
        z-index: 9;
        margin-top:-4px;
      }
      .upload-file-list {
        max-height: 120px;
        overflow-y: auto;
        padding-right:30px;
        .el-upload-list__item{
          margin-bottom: 0px !important;
        }
      }
    }
  }
}
.check-detection-drawer{
  .el-tabs__content{
        overflow: visible;
      }
}
</style>