<template>
  <div class="cooperatorDatails">
    <el-menu
      :default-active="activeIndex"
      class="el-menu-demo"
      mode="horizontal"
      @select="handleSelect"
      active-text-color="#5181F6"
    >
      <el-menu-item index="1">{{
        $t("message.laborMange.essential")
      }}</el-menu-item>
      <el-menu-item index="2">{{
        $t("message.cooperationUnit.qualification")
      }}</el-menu-item>
      <el-menu-item index="3">{{
        $t("message.cooperationUnit.badRecord")
      }}</el-menu-item>
    </el-menu>
    <div v-if="activeIndex == '1'" class="content_wrap">
      <vue-scroll style="height: 650px">
        <el-table
          :data="enterpriseInfo"
          :show-header="false"
          border
          stripe
          style="width: 100%"
        >
          <el-table-column prop="fieldName" min-width="15%"> </el-table-column>
          <el-table-column prop="value" min-width="35%"> </el-table-column>
          <el-table-column prop="fieldName2" min-width="15%"> </el-table-column>
          <el-table-column prop="value2" min-width="35%">
            <template slot-scope="scope">
              <div
                v-if="scope.row.value2 && scope.row.value2.indexOf('http://') >= 0"
                class="showImg_wrap"
              >
                <!-- <img
                  v-for="(item, index) in getUrl(scope.row.value2, 1)"
                  :key="index"
                  :src="item"
                  class="showImg"
                  @click="showImgBtn(item)"
                /> -->
                <img
                  :src="scope.row.value2"
                  class="showImg"
                  @click="showImgBtn(scope.row.value2)"
                />
              </div>

              <div v-else>
                {{ scope.row.value2 }}
              </div>
            </template>
          </el-table-column>
        </el-table>
      </vue-scroll>
    </div>
    <div v-if="activeIndex == '2'" class="content_wrap">
      <!-- <el-button
        class="addQualificationBtn"
        type="primary"
        size="medium"
        @click="addBtn(1)"
        >新增</el-button
      > -->
      <el-table
        :data="qualificationList"
        stripe
        style="width: 100%"
        border
        :header-cell-style="{ background: '#F7F8FA' }"
      >
        <el-table-column
          type="index"
          :label="$t('message.cooperationUnit.index')"
          width="60"
          align="center"
        >
        </el-table-column>
        <el-table-column
          prop="fileName"
          :label="$t('message.cooperationUnit.aptitudeFileName')"
        >
        </el-table-column>
        <el-table-column
          prop="fileNumber"
          :label="$t('message.cooperationUnit.aptitudeFileNumber')"
        >
        </el-table-column>
        <el-table-column
          prop="fileUrl"
          :label="$t('message.cooperationUnit.aptitudeFile')"
        >
          <template slot-scope="scope">
            <!-- <img
                v-for="(url,index) in getUrl(scope.row.fileUrl, 2)"
                :key="index"
                :src="url[index]"
                class="showImg"
                @click="
                      bigImageDialog = true;
                      bigImageUrl = url[index];
                    "
              /> -->
            <img
                :src="scope.row.fileUrl"
                class="showImg"
                @click="
                      bigImageDialog = true;
                      bigImageUrl = scope.row.fileUrl;
                    "
              />
            <!-- <a
              :href="url[index]"
              download
              v-for="(url,index) in getUrl(scope.row.fileUrl, 2)"
              :key="index"
              target="self"
              class="qualificationHref"
            > -->
              <!-- <img 
                v-if="scope.row.fileUrl && matchResult"
                :key="index"
                :src="url[index]"
                class="showImg"
              /> -->
              <!-- {{ matchResult ? "" : url[index]}}
            </a> -->
          </template>
        </el-table-column>
        <el-table-column
          prop="remarks"
          :label="$t('message.cooperationUnit.remark')"
        >
        </el-table-column>
      </el-table>
    </div>
    <div class="qualificationDialog">
      <el-dialog
        title="新增"
        :visible.sync="qualificationDialog"
        :modal-append-to-body="false"
        width="30%"
      >
        <el-form
          :model="qualificationForm"
          :rules="qualificationFormRules"
          ref="qualificationForm"
          label-width="120px"
            size="medium"
            class="dialogFormBox"
        >
          <el-form-item label="资质文件名称"  prop="fileName">
            <el-input
              v-model="qualificationForm.fileName"
              autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="资质文件编号"
            prop="fileNumber"
          >
            <el-input
              v-model="qualificationForm.fileNumber"
              autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item label="上传资质文件"  prop="fileUrl">
            <el-upload
              class="upload-demo"
              :action="$store.state.UPLOADURL"
              :on-preview="showImgBtn"
              :on-remove="handleRemove"
              :on-success="handleSuccess"
              accept="image/jpg,image/jpeg,image/png"
              :before-upload="handleBeforeUpload"
              name="files"
              multiple
              ref="upload"
              :file-list="fileList"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-form-item>
          <el-form-item label="备注"  prop="remarks">
            <el-input
              v-model="qualificationForm.remarks"
              autocomplete="off"
            ></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="qualificationDialog = false">取 消</el-button>
          <el-button type="primary" @click="addQualification">确 定</el-button>
        </div>
      </el-dialog>
    </div>
    <div v-if="activeIndex == '3'" class="content_wrap">
      <el-button
        v-permission="{key: 'hzdw_add_bad', menuPath: '/project/summary/cooperationUnit'}"
        class="addBadRecordBtn"
        type="primary"
        size="medium"
        @click="addBtn(2)"
        >新增</el-button
      >
      <el-table
        :data="badRecordList"
        stripe
        style="width: 100%"
        border
        :header-cell-style="{ background: '#F7F8FA' }"
        ref="badRecordList"
      >
        <el-table-column
          type="index"
          :label="$t('message.cooperationUnit.index')"
          width="60"
          align="center"
        >
        </el-table-column>
        <el-table-column
          prop="ariseTime"
          :label="$t('message.cooperationUnit.occurrenceTime')"
        >
        </el-table-column>
        <el-table-column
          prop="ariseMatter"
          :label="$t('message.cooperationUnit.mattersHappened')"
        >
        </el-table-column>
        <el-table-column
          prop="ariseReason"
          :label="$t('message.cooperationUnit.occurrenceReason')"
        >
          <template slot-scope="scope">
            {{ scope.row.ariseReason }}
          </template>
        </el-table-column>
        <el-table-column
          prop="remarks"
          :label="$t('message.cooperationUnit.remark')"
        >
        </el-table-column>
      </el-table>
    </div>
    <div class="badRecordDialog">
      <el-dialog
        title="新增"
        :visible.sync="badRecordDialog"
        :modal-append-to-body="false"
        width="30%"
      >
        <el-form
          :model="badRecordForm"
          :rules="badRecordFormRules"
          ref="badRecordForm"
          label-width="100px"
            size="medium"
            class="dialogFormBox"
        >
          <el-form-item label="发生事项"  prop="ariseMatter">
            <el-input
              v-model="badRecordForm.ariseMatter"
              autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item label="发生原因"  prop="ariseReason">
            <el-input
              v-model="badRecordForm.ariseReason"
              autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item label="发生时间"  prop="ariseTime">
            <div class="block">
              <span class="demonstration"></span>
              <el-date-picker
                v-model="badRecordForm.ariseTime"
                type="datetime"
                placeholder="选择日期时间"
                value-format="yyyy-MM-dd HH:mm:ss"
              >
              </el-date-picker>
            </div>
          </el-form-item>
          <el-form-item label="备注"  prop="remarks">
            <el-input
              v-model="badRecordForm.remarks"
              autocomplete="off"
            ></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="badRecordDialog = false">取 消</el-button>
          <el-button type="primary" @click="addBadRecord">确 定</el-button>
        </div>
      </el-dialog>
    </div>
    <!-- 查看大图 -->
    <div
      v-if="bigImageDialog"
      class="bigImageDialog"
      @click="bigImageDialog = false"
    >
      <div class="bigImageContent">
        <img width="auto" height="auto" :src="bigImageUrl" alt />
      </div>
    </div>
  </div>
</template>
<script>
import {
  getEnterpriseInfoByIdApi,
  getQueryByIdListApi,
  getBadRecordApi,
  addEnterpriseQualification,
  addEnterpriseBadRecord,
} from "@/assets/js/api/cooperationUnit";
export default {
  props: ["detailId", "projectEnterpriseId"],
  data() {
    return {
      activeIndex: "1",
      projectSn: "",
      enterpriseInfo: this.$t("message.projectInfo.enterpriseInfo"),
      fileUrl: "",
      qualificationList: [],
      badRecordList: [],
      bigImageDialog: false,
      bigImageUrl: "",
      qualificationDialog: false, // 新增企业资质弹窗
      qualificationForm: {
        fileName: "", //资质文件名
        fileNumber: "", // 资质文件编号
        fileUrl: "", // 文件路径
        remarks: "", // 备注
      },
      fileList: [],
      qualificationFormRules: {
        fileName: [
          { required: true, message: "请输入资质文件名称", trigger: "blur" },
        ],
        fileNumber: [
          { required: true, message: "请输入资质文件编号", trigger: "blur" },
        ],
        fileUrl: [{ required: true, message: "请选择文件", trigger: "blur" }],
      },
      matchResult: "",
      badRecordDialog: false, //新增不良记录弹窗
      badRecordForm: {
        ariseMatter: "", //发生事项
        ariseReason: "", // 发生原因
        ariseTime: "", // 发生时间
        remarks: "", // 备注
      },
      badRecordFormRules: {
        ariseMatter: [
          { required: true, message: "请输入发生事项", trigger: "blur" },
        ],
        ariseReason: [
          { required: true, message: "请输入发生原因", trigger: "blur" },
        ],
        ariseTime: [
          { required: true, message: "请选择发生时间", trigger: "blur" },
        ],
      },
      infoEnterpriseId: ""
    };
  },
  created() {
    this.projectSn = this.$store.state.projectSn;
    this.fileUrl = this.$store.state.FILEURL;
    this.getEnterpriseInfoById();
  },
  methods: {
    //切换组件
    handleSelect(value) {
      this.activeIndex = value;
      if (value == 1) {
        this.getEnterpriseInfoById();
      } else if (value == 2) {
        this.getQueryById();
      } else if (value == 3) {
        setTimeout(() => {
          this.getBadRecord();
        }, 200);
      }
    },

    //获取企业信息
    getEnterpriseInfoById() {
      let data = {
        enterpriseId: this.$props.detailId,
        projectSn: this.$store.state.projectSn,
      };
      getEnterpriseInfoByIdApi(data).then((res) => {
        if (res.code == 200) {
          this.enterpriseInfo = [
            {
              fieldName: this.$t("message.laborMange.theNameOfFirm"),
              fieldName2: this.$t("message.laborMange.photosOfQualification"),
              value: res.result.enterpriseName,
              value2:
                res.result.enterpriseQualificationUrl &&
                res.result.enterpriseQualificationUrl,
            },
            {
              fieldName: this.$t("message.laborMange.formOfBusiness"),
              fieldName2: this.$t("message.laborMange.legalRepresentative"),
              value:
                res.result.enterpriseTypeId == 1
                  ? this.$t("message.cooperationUnit.subpackage1")
                  : res.result.enterpriseTypeId == 2
                  ? this.$t("message.cooperationUnit.subpackage2")
                  : res.result.enterpriseTypeId == 3
                  ? this.$t("message.cooperationUnit.subpackage3")
                  : res.result.enterpriseTypeId == 4
                  ? this.$t("message.cooperationUnit.subpackage4")
                  : res.result.enterpriseTypeId == 5
                  ? this.$t("message.cooperationUnit.subpackage5")
                  : res.result.enterpriseTypeId == 6
                  ? this.$t("message.cooperationUnit.subpackage6")
                  : res.result.enterpriseTypeId == 7
                  ? this.$t("message.cooperationUnit.subpackage7")
                  : res.result.enterpriseTypeId == 8
                  ? this.$t("message.cooperationUnit.subpackage8")
                  : res.result.enterpriseTypeId == 9
                  ? this.$t("message.cooperationUnit.subpackage9")
                  : res.result.enterpriseTypeId == 10
                  ? this.$t("message.cooperationUnit.subpackage10")
                  : res.result.enterpriseTypeId == 11
                  ? this.$t("message.cooperationUnit.subpackage11")
                  : this.$t("message.cooperationUnit.subpackage12"),
              value2: res.result.enterpriseLegalPerson,
            },
            {
              fieldName: this.$t("message.laborMange.openingBank"),
              fieldName2: this.$t("message.laborMange.unifiedSocialCreditCode"),
              value: res.result.bankname,
              value2: res.result.socialCode,
            },
            {
              fieldName: this.$t("message.laborMange.numberOfRegistrant"),
              fieldName2: this.$t("message.laborMange.registeredCapital"),
              value: res.result.registerPersonPhoneTel,
              value2: res.result.registeredCapital,
            },
            {
              fieldName: this.$t("message.laborMange.legalPersonPhone"),
              fieldName2: this.$t("message.laborMange.bankAccount"),
              value: res.result.legalPersonTel,
              value2: res.result.bankcardnumber,
            },
            {
              fieldName: this.$t("message.laborMange.businessLicense"),
              fieldName2: this.$t("message.laborMange.businessNumber"),
              value: res.result.businessLicenseEndDate,
              value2: res.result.businessNumber,
            },
            {
              fieldName: this.$t("message.laborMange.enterpriseMailbox"),
              fieldName2: this.$t("message.laborMange.addressOfPlant"),
              value: res.result.enterpriseEmail,
              value2: res.result.enterpriseAddress,
            },
            {
              fieldName: this.$t("message.laborMange.laborCertificateNo"),
              fieldName2: this.$t("message.laborMange.safetyProductionLicense"),
              value: res.result.qualificationNumber,
              value2: res.result.enterpriseSafeAllow,
            },
            {
              fieldName: this.$t("message.laborMange.natureOfUnit"),
              fieldName2: "logo",
              value:
                res.result.enterpriseProperty == 1
                  ? this.$t("message.laborMange.stateOwnedBusiness")
                  : res.result.enterpriseProperty == 2
                  ? this.$t("message.laborMange.overseasInvestedEnterprises")
                  : res.result.enterpriseProperty == 3
                  ? this.$t("message.laborMange.collectiveEnterprises")
                  : this.$t("message.laborMange.privateEnterprise"),
              value2: res.result.logo ? res.result.logo : "",
            },
            {
              fieldName: this.$t("message.projectInfo.projectLeader"),
              fieldName2: this.$t("message.projectInfo.projectLeaderPhone"),
              value: res.result.projectDirectorName,
              value2: res.result.projectDirectorPhone,
            },
          ];
          this.infoEnterpriseId = res.result.id;
          console.log(this.enterpriseInfo,666777888)
        }
      });
    },
    //获取企业资质
    getQueryById() {
      let data = {
        // enterpriseId: this.$props.projectEnterpriseId,
        enterpriseId: this.infoEnterpriseId
      };
      getQueryByIdListApi(data).then((res) => {
        if (res.code == 200) {
          this.qualificationList = res.result;
          this.qualificationList.map(item => {
            if (!item.fileUrl.includes(this.$store.state.FILEURL)) {
              if(item.fileUrl.includes("name")){
                item.fileUrl = this.$store.state.FILEURL + JSON.parse(item.fileUrl)[0].url;
              } else {
                item.fileUrl = this.$store.state.FILEURL + item.fileUrl;
              }
            }
          })
        }
      });
    },
    // 新增按钮
    addBtn(type) {
      // type 1新增企业资质按钮 2新增不良记录按钮
      if (type === 1) {
        this.qualificationDialog = true;
        this.$nextTick(() => {
          this.$refs.qualificationForm.resetFields();
        });
      } else if (type === 2) {
        this.badRecordDialog = true;
        this.$nextTick(() => {
          this.$refs.badRecordForm.resetFields();
        });
      }
    },
    // 新增企业资质
    addQualification() {
      this.$refs.qualificationForm.validate((valid) => {
        console.log('新增的参数',this.qualificationForm);
        if (valid) {
          let data = this.qualificationForm;
          // (data.enterpriseId = this.$props.projectEnterpriseId),
          data.enterpriseId = this.infoEnterpriseId;
            addEnterpriseQualification(data).then((res) => {
              // console.log('新增成功了吗',res)
              this.getQueryById();
              this.$refs.upload.clearFiles();
              this.fileList = [];
              this.$refs.qualificationForm.resetFields();
            });
          this.qualificationDialog = false;
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },

    //获取不良记录
    getBadRecord() {
      let data = {
        enterpriseId: this.$props.projectEnterpriseId,
        // enterpriseId: this.$props.detailId,
      };
      getBadRecordApi(data).then((res) => {
        if (res.code == 200) {
          console.log(res);
          this.badRecordList = res.result;
          this.$forceUpdate();
          this.$refs.badRecordList.doLayout();
        }
      });
    },
    // 新增不良记录
    addBadRecord() {
      this.$refs.badRecordForm.validate((valid) => {
        console.log(this.badRecordForm);
        if (valid) {
          let data = this.badRecordForm;
          // (data.enterpriseId = this.$props.detailId),
          (data.enterpriseId = this.$props.projectEnterpriseId),
            addEnterpriseBadRecord(data).then((res) => {
              this.getBadRecord();
              this.$refs.badRecordForm.resetFields();
            });
          this.badRecordDialog = false;
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    // 资质文件上传成功
    handleSuccess(file) {
      console.log('上传成功放回的值',file)
      let data = { name: file.data[0].filename, url: file.data[0].imageUrl };
      // let data = { name: file.data[0].fileInfo.attr.originalFilename, url: file.data[0].imageUrl };
      this.fileList.push(data);
      this.qualificationForm.fileUrl =
        this.fileList.length > 0 ? JSON.stringify(this.fileList) : "";
      console.log(this.qualificationForm);
      this.$refs.qualificationForm.clearValidate();
    },
    // 资质文件删除成功
    handleRemove(file) {
      console.log(this.qualificationForm);
      let url = file.url ? file.url : file.response.data[0].imageUrl;
      for (let i = 0; i < this.fileList.length; i++) {
        if (this.fileList[i].url == url) {
          this.fileList.splice(i, 1);
        }
      }
      console.log(this.fileList);
    },
    // 判断上传的是否为图片
    handleBeforeUpload(file) {
        var img = file.name.substring(file.name.lastIndexOf('.') + 1)
        const suffix = img === 'jpg'
        const suffix2 = img === 'png'
        const suffix3 = img === 'jpeg'
        const isLt1M = file.size / 1024 / 1024 < 1;
       if (!suffix && !suffix2 && !suffix3) {
           this.$message.error("只能上传图片！");
           return false
       }
       // 可以限制图片的大小
       if (!isLt1M) {
           this.$message.error('上传图片大小不能超过 1MB!');
       }
       return suffix || suffix2 || suffix3
    },

    //截取图片地址
    getUrl(url, type) {
      if (url == null || url == undefined || url == "") return;
      if (type === 1) {
        let arr = url.split(",");
        let showArr = [];
        for (let i = 0; i < arr.length; i++) {
          let showUrl = arr[i].split("*")[1];
          showArr.push(this.fileUrl + showUrl);
        }
        return showArr;
      } else if(type == 2) {
        let arr = JSON.parse(url);
        // this.matchResult = arr.match("(.+?).(png|jpg|gif)");
        // console.log('this.matchResult',this.matchResult)
        // arr = arr.split(",");
        let showArr = [];
        showArr = arr.map((item)=>{
          let showUrl = item.url
          let showArray = []
          showArray.push(this.fileUrl + showUrl);
          return showArray
        })
        return showArr;
        
        // for (let i = 0; i < arr.length; i++) {
        //   let showUrl = arr[i].url;
        //   // showArr.push(this.fileUrl + showUrl);
        //   let a  = showUrl.split(".")[1]
        //   if( a === 'png'|| a === 'jpg' ||  a ==='gif'){
        //     showArr.push(this.fileUrl + showUrl);
        //   }else{
        //     this.matchResult = showUrl
        //   }
        // }
        // console.log('showArr',showArr)
        
      }
    },

    //查看大图
    showImgBtn(value) {
      this.bigImageDialog = true;
      this.bigImageUrl = value;
    },
  },
};
</script>
<style lang="less" scoped>
.el-menu--horizontal > .el-menu-item {
  height: 40px;
  line-height: 40px;
}
.content_wrap {
  width: 100%;
  height: 100%;
  box-sizing: border-box;
  padding: 30px 20px;
}
.showImg_wrap {
  display: flex;
  align-items: center;
}
.showImg {
  width: 50px;
  height: 45px;
  margin: 0 10px 0 0;
  cursor: pointer;
}
.bigImageDialog {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  text-align: center;
  z-index: 1000000;
  overflow-y: auto;
  // padding-bottom: 50px;
  height: 100%;
  .bigImageContent {
    height: 100%;
    margin: 0 auto;
    text-align: center;
  }
  img {
    // margin-top: 10%;
    position: relative;
    top: 10%;
    max-height: 80%;
    max-width: 80%;
  }
}
.qualificationHref {
  text-decoration: none;
  color: blue;
  display: block;
}
.addQualificationBtn,
.addBadRecordBtn {
  margin-top: -20px;
  margin-bottom: 10px;
}
</style>