<template>
  <div class="fullHeight">
    <div class="searchBox whiteBlock">
      <el-form
        :inline="true"
        size="medium"
        :model="searchForm"
        ref="searchForm"
      >
        <el-form-item label="" prop="eduType">
          <el-select
            v-model="searchForm.eduType"
            :placeholder="$t('message.laborDev.allType')"
            filterable
            clearable
          >
            <el-option
              :label="item"
              :value="index + 1"
              v-for="(item, index) in educateTypeList"
              :key="index"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="" prop="eduCourseName">
          <el-input
            v-model="searchForm.eduCourseName"
            :placeholder="$t('message.laborDev.searchTranTopic')"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" plain @click="loadCardData">
            {{ $t("message.personnelPosition.beaconManage.query") }}
          </el-button>
          <el-button type="warning" plain @click="resetForm">
            {{ $t("message.personnelPosition.beaconManage.refresh") }}
          </el-button>
          <el-button type="primary" @click="addPoint">
            {{ $t("message.laborDev.addSafeTrain") }}
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="table_wrap whiteBlock">
      <el-table class="tables" :data="pointList">
        <el-table-column
          type="index"
          width="50"
          align="center"
          :label="$t('message.personnelPosition.beaconManage.table.index')"
        ></el-table-column>
        <el-table-column
          prop="eduTime"
          :label="$t('message.laborDev.trainDate')"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="eduType"
          :label="$t('message.laborDev.educateType')"
          align="center"
        >
          <template slot-scope="scope">
            {{ educateTypeList[scope.row.eduType - 1] }}
          </template>
        </el-table-column>
        <el-table-column
          prop="eduCourseName"
          :label="$t('message.laborDev.trainTopic')"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="eduClasshour"
          :label="$t('message.laborDev.trainTime')"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="eduTeacher"
          :label="$t('message.laborDev.trainPerson')"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="workernum"
          :label="$t('message.laborMange.numberOfPeople')"
          align="center"
        ></el-table-column>
        <!-- <el-table-column
          prop="eduContent"
          :label="$t('message.laborDev.remarks')"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="eduPhoto"
          :label="$t('message.laborDev.remarks')"
          align="center"
        >
          <template slot-scope="scope">
            <img :src="scope.row.eduPhoto" alt="附件" srcset="" />
          </template>
        </el-table-column> -->
        <el-table-column
          :label="$t('message.personnelPosition.beaconManage.table.operation')"
          align="center"
          width="300"
        >
          <template slot-scope="scope">
            <div class="tableBtns">
              <div @click="uploadPoint(scope.row)" class="operationText">
              <img
                  src="@/assets/images/icon_upload.png"
                  width="15px"
                  height="15px"
                />
                <span><a :href="uploadaurl" class="uploadpoint">下载</a></span>
              </div>
              <div @click="editPoint(scope.row)" class="operationText">
                <img
                  src="@/assets/images/icon-edit.png"
                  width="15px"
                  height="15px"
                />
                <span>{{
                  $t("message.personnelPosition.beaconManage.table.edit")
                }}</span>
              </div>
              <div @click="removePoint(scope.row)" class="operationText">
                <img
                  src="@/assets/images/icon-delete.png"
                  width="15px"
                  height="15px"
                />
                <span>{{
                  $t("message.personnelPosition.beaconManage.table.delete")
                }}</span>
              </div>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        class="pagerBox"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageNo"
        :page-sizes="$store.state.PAGESIZRS"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next"
        :total="total"
        background
      ></el-pagination>
    </div>
    <!-- 添加卡片弹框 -->
    <el-dialog
      :modal-append-to-body="false"
      :title="cardDialogTitle"
      :visible.sync="cardDialog"
      width="1167px"
    >
      <div class="dialog_content">
        <el-form
          size="medium"
          :model="cardForm"
          ref="cardForm"
          :rules="cardFormRules"
          :inline="true"
          label-width="120px"
          class="dialogFormBox dialogFormBox2"
        >
          <el-form-item
            :label="$t('message.laborDev.educateType')"
            prop="eduType"
          >
            <el-select
              v-model="cardForm.eduType"
              :placeholder="$t('message.laborDev.allType')"
            >
              <el-option
                :label="item"
                :value="index + 1"
                v-for="(item, index) in educateTypeList"
                :key="index"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            :label="$t('message.laborDev.trainTopic')"
            prop="eduCourseName"
          >
            <el-input
              v-model="cardForm.eduCourseName"
              :placeholder="$t('message.personnelPosition.please_enter')"
            ></el-input>
          </el-form-item>
          <el-form-item
            :label="$t('message.laborDev.trainDate')"
            prop="eduTime"
          >
            <el-date-picker
              v-model="cardForm.eduTime"
              type="date"
              :placeholder="$t('message.laborMange.pleaseSelectADate')"
              value-format="yyyy-MM-dd"
              style="width: 100%"
            ></el-date-picker>
          </el-form-item>
          <el-form-item
            :label="$t('message.laborDev.trainDateTime')"
            prop="eduDateTime"
          >
            <el-time-select
              class="startTime"
              placeholder="起始时间"
              v-model="cardForm.eduStartTime"
              :picker-options="{
                start: '08:30',
                step: '00:15',
                end: '18:30',
                maxTime: cardForm.eduEndTime
              }">
            </el-time-select>
            <el-time-select
              class="endTime"
              placeholder="结束时间"
              v-model="cardForm.eduEndTime"
              :picker-options="{
                start: '08:30',
                step: '00:15',
                end: '18:30',
                minTime: cardForm.eduStartTime
              }">
            </el-time-select>
          </el-form-item>
          <el-form-item
            :label="$t('message.laborDev.trainPerson')"
            prop="eduTeacher"
          >
            <el-input
              v-model="cardForm.eduTeacher"
              :placeholder="$t('message.personnelPosition.please_enter')"
            ></el-input>
          </el-form-item>
          <el-form-item
            :label="$t('message.laborDev.trainTime')"
            prop="eduClasshour"
          >
            <el-input
              v-model="cardForm.eduClasshour"
              :placeholder="$t('message.personnelPosition.please_enter')"
            ></el-input>
          </el-form-item>
          <el-form-item :label="$t('message.laborDev.trainPersonNum')">
            <el-input :value="cardForm.list.length" disabled></el-input>
          </el-form-item>
          <el-form-item :label="$t('message.laborDev.signInInfo')" prop="list">
            <el-button type="primary" @click="selectWorkerDialog = true">
              {{ $t("message.laborDev.selectWorker") }}
            </el-button>
             <!-- 添加上传相关材料 -->
            <el-upload
             name="files"
              class="upload-demo uploadBtn"
              :action="$store.state.UPLOADURL"
              multiple
              :file-list="fileList"
              :on-preview="handlePreview"
              :on-success="handleSuccess"
              :show-file-list="false"
            >
              <el-button type="primary">材料上传</el-button>
            </el-upload>
          </el-form-item>
          <!-- 培训照片 -->
          <el-form-item :label="$t('message.laborDev.photo')" prop="photo" >
            <div class="form-photo" >
              <el-upload
                v-for="i in 3" :key="i"
                name="files"
                class="photoUpload"
                :action="$store.state.UPLOADURL"
                :show-file-list="false"
                :on-success="file => handleUpload(file, i)"
                :before-upload="beforeAvatarUpload">
                <img v-if="cardForm[`edu${i === 1 ? 'Before': i === 2 ? 'In' : 'After'}Photo`]" 
                  :src="$store.state.FILEURL + cardForm[`edu${i === 1 ? 'Before': i === 2 ? 'In' : 'After'}Photo`]" 
                  class="photo">
                <template v-else> 
                  <i  class="el-icon-plus avatar-uploader-icon"></i>
                  <span>培训{{i === 1 ? '前' : i === 2 ? '中' : '后'}}</span>
                </template>
              </el-upload>
            </div>
          </el-form-item>
          <el-table
            class="tables dialogTable"
            :data="cardForm.list"
            height="300"
          >
            <!-- <el-table-column type="index" width="50" align="center"
                                        :label="$t('message.personnelPosition.beaconManage.table.index')"></el-table-column> -->
            <el-table-column :label="$t('message.laborMange.compellation')">
              <template slot-scope="scope">{{ scope.row.workerName }}</template>
            </el-table-column>
            <el-table-column prop="sex" :label="$t('message.laborMange.sex')">
              <template slot-scope="scope">{{
                scope.row.sex == 1
                  ? $t("message.laborMange.man")
                  : $t("message.laborMange.female")
              }}</template>
            </el-table-column>
            <!-- <el-table-column
              prop="idCard"
              :label="$t('message.laborMange.IdNumber')"
            >
            </el-table-column> -->
            <el-table-column prop="age" :label="$t('message.laborMange.age')">
            </el-table-column>
            <el-table-column
              prop="teamName"
              :label="$t('message.laborMange.team')"
            >
            </el-table-column>
            <el-table-column
              prop="isQualified"
              :label="$t('message.laborDev.isQualified')"
            >
              <template slot-scope="scope">
                <el-select
                  @change="changeQualified(scope.$index, scope.row.isQualified)"
                  class="tableInput"
                  v-model="scope.row.isQualified"
                  :placeholder="$t('message.laborDev.allType')"
                >
                  <el-option
                    :label="$t('message.laborMange.qualified')"
                    :value="1"
                  >
                  </el-option
                  ><el-option
                    :label="$t('message.laborMange.disqualification')"
                    :value="2"
                  >
                  </el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column prop="score" :label="$t('message.laborDev.score')">
              <!-- (value,scope.row.$index) -->
              <template slot-scope="scope">
                <el-input
                  @input="changeScore(scope.$index, scope.row.score)"
                  class="tableInput"
                  v-model="scope.row.score"
                  :placeholder="$t('message.personnelPosition.please_enter')"
                ></el-input>
              </template>
            </el-table-column>

            <el-table-column
              :label="
                $t('message.personnelPosition.beaconManage.table.operation')
              "
              align="center"
              width="100"
            >
              <template slot-scope="scope">
                <div class="tableBtns">
                  <div
                    @click="deleteSelectWorker(scope.$index)"
                    class="operationText"
                  >
                    <img
                      src="@/assets/images/icon-delete.png"
                      width="15px"
                      height="15px"
                    />
                    <span>{{
                      $t("message.personnelPosition.beaconManage.table.delete")
                    }}</span>
                  </div>
                </div>
              </template>
            </el-table-column>
          </el-table>
          <div class="dialog-footer">
            <el-button
              class="cancleBtn"
              @click="cardDialog = false"
              icon="el-icon-circle-close"
              size="medium"
              >{{ $t("message.personnelPosition.cancel") }}
            </el-button>
            <!-- 取消 -->
            <el-button
              type="primary"
              icon="el-icon-circle-check"
              @click="saveCardFn"
              size="medium"
              >{{ $t("message.personnelPosition.determine") }}
            </el-button>
            <!-- 确定 -->
          </div>
        </el-form>
      </div>
    </el-dialog>
    <!-- 选择工人弹框 -->
    <el-dialog
      :modal-append-to-body="false"
      :title="$t('message.laborDev.selectWorker')"
      :visible.sync="selectWorkerDialog"
      width="967px"
    >
      <div class="dialog_content">
        <selectWorker
          :personType="1"
          @getData="getWorkerData"
          v-if="selectWorkerDialog"
          @close="closeSelectWorkerDialog"
        ></selectWorker>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import selectWorker from "@/components/selectWorker";
import { getWorkerInfoListApi } from "@/assets/js/api/personnelPosition.js";
import {
  workerSafeEducationListApi,
  workerSafeEducationAddApi,
  workerSafeEducationDetailApi,
  workerSafeEducationEditApi,
  workerSafeEducationDeleteApi,
} from "@/assets/js/api/laborPerson.js";
export default {
  components: { selectWorker },
  data() {
    return {
      uploadaurl:'',
      fileList:[],
      searchForm: {
        eduType: "",
        eduCourseName: "",
      },
      pointList: [],
      total: 0,
      pageNo: 1,
      pageSize: 10,
      cardDialogTitle: "",
      cardDialog: false,
      cardForm: {
        uploadAttachments:"",
        eduAddr: "",
        eduClasshour: 0,
        eduContent: "",
        eduCourseName: "",
        eduPhoto: "",
        eduBeforePhoto: "",
        eduInPhoto: "",
        eduAfterPhoto: "",
        eduTeacher: "",
        eduTime: "",
        eduStartTime: '',
        eduEndTime: '',
        eduType: 1,
        list: [],
        workernum: 0,
        projectSn: this.$store.state.projectSn,
      },
      cardFormRules: {
        eduCourseName: [
          {
            required: true,
            message: this.$t("message.personnelPosition.mandatory"),
            trigger: "blur",
          },
        ],
        eduTime: [
          {
            required: true,
            message: this.$t("message.personnelPosition.mandatory"),
            trigger: "blur",
          },
        ],
        list: [
          {
            required: true,
            message: this.$t("message.personnelPosition.mandatory"),
            trigger: "blur",
          },
        ],
      },
      isAdd: false,
      allPersonList: [],
      educateTypeList: this.$t("message.laborDev.educateTypeList"),
      selectWorkerDialog: false,
    };
  },
  mounted() {
    this.loadAllPerson();
    this.loadCardData();
    let xxx = this.$store.state.FILEURL
    console.log('url',xxx)
  },
  methods: {
    handleUpload(res, num) {
      const imageUrl = res.data[0].imageUrl
      this.cardForm[`edu${num === 1 ? 'Before': num === 2 ? 'In' : 'After'}Photo`] = imageUrl
      console.log(this.eduPhoto1,this.eduPhoto2,this.eduPhoto3, num);
    },
    handlePreview(file,type){
      //  console.log('file',file)
      // console.log('fileList',type)
    },
    handleSuccess(file,fileList){
      console.log('成功的file',file)
      this.cardForm.uploadAttachments = file.data[0].filename
      if(file.status == "SUCCESS"){
        this.$message({
          message: '相关材料上传成功！',
          type: 'success'
        });
      }else{
        this.$message({
          message: '上传失败，请重新上传！',
          type: 'error'
        });
      }
    },
    changeScore(index, value) {
      console.log("changeScore", value, index);
      var json = this.cardForm.list[index];
      this.$set(json, "score", value);
      this.$set(this.cardForm.list, index, json);

      this.$forceUpdate();
    },
    changeQualified(index, value) {
      // console.log('changeQualified',value,index)
      //   console.log(this.cardForm.list)
      var json = this.cardForm.list[index];
      this.$set(json, "isQualified", value);
      // this.cardForm.list[index]=json
      this.$set(this.cardForm.list, index, json);
      // console.log(this.cardForm)
      this.$forceUpdate();
    },
    deleteSelectWorker(index) {
      this.cardForm.list.splice(index, 1);
    },
    closeSelectWorkerDialog() {
      this.selectWorkerDialog = false;
    },
    getWorkerData(data) {
      //去重，已经添加过的人员就不添加了

      var arr = this.cardForm.list;
      var arr2 = [];
      data.forEach((item2) => {
        if (arr.length > 0) {
          var onoff = true;
          arr.forEach((item) => {
            if (item.id == item2.id) {
              onoff = false;
            }
            if (item.workerId == item2.id) {
              onoff = false;
            }
          });
          if (onoff) {
            item2.isQualified = "";
            item2.score = "";
            arr2.push(item2);
          }
        } else {
          item2.isQualified = "";
          item2.score = "";
          arr2.push(item2);
        }
      });

      this.cardForm.list = arr.concat(arr2);
      //   this.cardForm.workernum = this.cardForm.list.length;
    },
    //获取所有人员
    loadAllPerson() {
      getWorkerInfoListApi({
        projectSn: this.$store.state.projectSn,
        userEnterpriseId: this.$store.state.userInfo.userEnterpriseId,
      }).then((res) => {
        this.allPersonList = res.result;
      });
    },
    addPoint() {
      this.isAdd = true;
      this.cardDialog = true;
      this.$nextTick(() => {
        this.$refs["cardForm"].resetFields();
        delete this.cardForm.id;
      });

      this.cardDialogTitle = this.$t("message.laborDev.add2");
    },
    editPoint(item) {
      this.isAdd = false;
      this.cardDialogTitle = this.$t("message.laborDev.btn_edit"); //编辑
      this.cardDialog = true;
      workerSafeEducationDetailApi({
        id: item.id,
        projectSn: this.$store.state.projectSn,
      }).then((res) => {
        this.cardForm = res.result.workerSafeEducation;
        console.log(res);
        this.cardForm.list = res.result.list;
      });
    },
    // 下载材料
    uploadPoint(item){
      console.log('item',item)
      if(item.uploadAttachments != null){
        this.uploadaurl = this.$store.state.FILEURL + item.uploadAttachments
      }else{
        this.$message({
          message: '当前没有相关材料！',
          type: 'error'
        });
        this.uploadaurl = window.location
      }
    },
    removePoint(item) {
      this.$confirm(
        this.$t("message.personnelPosition.beaconManage.table.confirmText") +
          "【" +
          item.eduCourseName +
          "】?",
        this.$t("message.personnelPosition.beaconManage.table.Tips"),
        {
          type: "warning",
        }
      ).then(() => {
        workerSafeEducationDeleteApi({ id: item.id }).then((res) => {
          this.loadCardData();
          this.$message.success(
            this.$t("message.personnelPosition.delete_success")
          ); //删除成功!
        });
      });
    },
    //获取卡片列表
    loadCardData() {
      workerSafeEducationListApi({
        projectSn: this.$store.state.projectSn,
        pageNo: this.pageNo,
        pageSize: this.pageSize,
        eduType: this.searchForm.eduType,
        eduCourseName: this.searchForm.eduCourseName,
        userEnterpriseId: this.$store.state.userInfo.userEnterpriseId,
      }).then((res) => {
        console.log(res.result);
        this.pointList = res.result.records;
        this.total = res.result.total;
      });
    },
    //添加或编辑卡片
    saveCardFn() {
      this.$refs["cardForm"].validate((valid) => {
        if (valid) {
          if (this.cardForm.list.length == 0) {
            this.$message.error(this.$t("message.laborMange.errorHint"));
            return;
          }
          this.cardForm.workernum = this.cardForm.list.length;
          var json = this.cardForm;
          var arr = [];
          console.log(json.list);
          json.list.forEach((element) => {
            var item = {
              isQualified: element.isQualified,
              score: element.score,
              workerId: this.isAdd ? element.id : element.workerId,
              projectSn: this.$store.state.projectSn,
            };
            if (!this.isAdd) {
              item.eduId = this.cardForm.id;
              item.id = element.id;
            }
            arr.push(item);
          });
          json.list = arr;
          if (this.isAdd) {
            console.log(json);
            workerSafeEducationAddApi(json).then((res) => {
              this.cardDialog = false;
              this.loadCardData();
              this.$message.success(
                this.$t("message.personnelPosition.add_success")
              ); //添加成功！
            });
          } else {
            // console.log(this.cardForm)
            workerSafeEducationEditApi(this.cardForm).then((res) => {
              this.cardDialog = false;
              this.loadCardData();
              this.$message.success(
                this.$t("message.personnelPosition.edit_success")
              ); //编辑成功！
            });
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    resetForm() {
      this.$refs["searchForm"].resetFields();
      this.loadCardData();
    },

    //查看条数
    handleSizeChange(val) {
      this.pageSize = val;
      this.loadCardData();
    },
    //查看页
    handleCurrentChange(val) {
      this.pageNo = val;
      this.loadCardData();
    },
  },
};
</script>
<style lang="less" scoped>
.uploadpoint{
  text-decoration: none;
  color:black;
}
.uploadBtn{
  display: inline-block;
  margin-left: 10px;
}
.dialogFormBox2 {
  width: 95% !important;
}
.dialogTable {
  min-height: auto;
}
.tableInput {
  width: 100px !important;
  /deep/ .el-input {
    width: 100% !important;
  }
}
/deep/ .el-dialog {
  margin: 0 !important;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.form-photo{
  display: flex;
  flex-wrap: wrap;
  .photoUpload{
    margin-right: 10px;
    .photo{
      width: 100%;
      height: 100%;
    }
  }
}

/deep/.photoUpload .el-upload {
  position: relative;
  width: 80px;
  height: 80px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  overflow: hidden;
  cursor: pointer;
  span{
    position: relative;
    bottom: 36px;
  }
}
.avatar-uploader-icon {
  font-size: 20px;
  color: #8c939d;
  width: 80px;
  height: 80px;
  line-height: 80px;
  text-align: center;
}
.startTime, .endTime{
  width: 160px !important;
  /deep/.el-input__inner{
    width: 140px;
  }
}
/deep/.el-date-editor{
  width: 120px;
}
</style>
