<template>
  <div class="fullHeight">
    <div class="searchBox whiteBlock">
      <el-form :inline="true" size="medium">
        <el-form-item prop="fineType">
          <el-select
            v-model="fineType"
            :placeholder="$t('message.laborMange.pleaseChoose')"
            clearable
          >
            <el-option
              :label="$t('message.laborMange.bonusSpaces')"
              :value="1"
            ></el-option>
            <el-option
              :label="$t('message.laborMange.debitNote')"
              :value="2"
            ></el-option>
            <el-option
              :label="$t('message.laborMange.ticket')"
              :value="3"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" plain @click="selectData"
            >{{ $t("message.laborMange.inquire") }}
          </el-button>
          <el-button size="medium" type="primary" @click="addTicket">{{
            $t("message.laborMange.add")
          }}</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="table_wrap whiteBlock">
      <el-table :data="tableData" class="tables" style="width: 100%">
        <el-table-column
          prop="enterpriseName"
          :label="$t('message.laborMange.projectName')"
          align="center"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          prop="fineNo"
          :label="$t('message.laborMange.serialNumber')"
          align="center"
        >
        </el-table-column>
        <el-table-column
          prop="violationNature"
          :label="$t('message.laborMange.type')"
          align="center"
        >
          <template slot-scope="scope">
            {{
              scope.row.fineType == 1
                ? $t("message.laborMange.award")
                : scope.row.fineType == 2
                ? $t("message.laborMange.withhold")
                : scope.row.fineType == 3
                ? $t("message.laborMange.fine")
                : ""
            }}
          </template>
        </el-table-column>
        <el-table-column
          prop="finePrice"
          :label="$t('message.laborMange.rewardsAndPunishmentAmount')"
          align="center"
        >
        </el-table-column>
        <el-table-column
          prop="violationTime"
          :label="$t('message.laborMange.creationTime')"
          align="center"
        >
        </el-table-column>
        <el-table-column align="center">
          <template slot-scope="scope">
            <div class="tableBtns">
              <div class="operationText" @click="detailBtn(scope.row)">
                <img
                  src="@/assets/images/xm_num.png"
                  width="15px"
                  height="15px"
                />
                <span>{{ $t("message.laborMange.details") }}</span>
              </div>
              <div class="operationText" @click="editBtn(scope.row)">
                <img
                  src="@/assets/images/icon-edit.png"
                  width="15px"
                  height="15px"
                />
                <span>{{ $t("message.laborMange.edit") }}</span>
              </div>
              <div class="operationText" @click="deleteBtn(scope.row)">
                <img
                  src="@/assets/images/icon-delete.png"
                  width="15px"
                  height="15px"
                />
                <span>{{ $t("message.laborMange.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="Number(total)"
        background
      ></el-pagination>
    </div>

    <!-- 新增处罚单弹窗 -->
    <el-dialog
      :modal-append-to-body="false"
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="996px"
    >
      <div class="dialog_content" id="printDemo">
        <div
          v-if="operateType != 3"
          class="flex"
          style="width: 55%; margin: 10px auto; justify-content: center"
        >
          <div style="width: 50px">{{ $t("message.laborMange.headline") }}：</div>
          <el-input
            :placeholder="$t('message.laborMange.placeholder2')"
            v-model="dialogForm.titleName"
          ></el-input>
        </div>
        <h2 v-else>{{ dialogForm.titleName }}</h2>
        <div class="flex" style="justify-content: center; margin-bottom: 20px">
          <div v-if="operateType != 3">{{ $t("message.laborMange.type") }}：</div>
          <el-select
            v-model="dialogForm.fineType"
            :placeholder="$t('message.laborMange.pleaseChoose')"
            v-if="operateType != 3"
          >
            <el-option :label="$t('message.laborMange.bonusSpaces')" :value="1"></el-option>
            <el-option :label="$t('message.laborMange.debitNote')" :value="2"></el-option>
            <el-option :label="$t('message.laborMange.ticket')" :value="3"></el-option>
          </el-select>
          <h3 v-else>
            {{
              dialogForm.fineType == 1
                ? $t('message.laborMange.bonusSpaces')
                : dialogForm.fineType == 2
                ? $t('message.laborMange.debitNote')
                : $t('message.laborMange.ticket')
            }}
          </h3>
        </div>
        <div class="flex">
          <div style="width: 60%" class="flex">
            <span>{{$t('message.laborMange.projectName')}}：</span>
            <span>{{ projectName }}</span>
          </div>
          <div style="width: 40%" class="flex">
            <span>{{$t('message.laborMange.serialNumber')}}：</span>
            <div v-if="operateType != 3">
              <el-input :placeholder="$t('message.laborMange.pleaseChoose')" v-model="dialogForm.fineNo">
              </el-input>
            </div>
            <span v-else>{{ dialogForm.fineNo }}</span>
          </div>
        </div>

        <table class="newTable">
          <tr colspan="10">
            <td colspan="2">
              {{$t('message.laborMange.by')}}{{
                dialogForm.fineType == 1
                  ? $t('message.laborMange.award')
                  : dialogForm.fineType == 2
                  ? $t('message.laborMange.withhold')
                  : $t('message.laborMange.fine')
              }}{{$t('message.laborMange.unit')}}
            </td>
            <td colspan="8" style="text-align: left">
              <div v-if="operateType != 3">
                <el-select
                  style="width: 100%"
                  filterable
                  v-model="dialogForm.enterpriseId"
                  :placeholder="$t('message.laborMange.pleaseChoose')"
                >
                  <el-option
                    v-for="(item, index) in unitList"
                    :key="index"
                    :label="item.enterpriseName"
                    :value="item.id"
                  ></el-option>
                </el-select>
              </div>
              <div v-else>{{ dialogForm.enterpriseName }}</div>
            </td>
          </tr>
          <tr colspan="10">
            <td colspan="2">
              {{ dialogForm.fineType == 1 ? $t('message.laborMange.award') : $t('message.laborMange.violation') }}{{$t('message.laborMange.nature')}}
            </td>
            <td colspan="3" style="width: 30%">
              <div v-if="operateType != 3">
                <el-input
                  :placeholder="$t('message.laborMange.placeholder2')"
                  type="textarea"
                  :rows="2"
                  v-model="dialogForm.violationNature"
                >
                </el-input>
              </div>
              <div v-else style="text-align: left">
                <pre>{{ dialogForm.violationNature }}</pre>
              </div>
            </td>
            <td colspan="2">
              {{ dialogForm.fineType == 1 ? $t('message.laborMange.award') : $t('message.laborMange.violation') }}{{$t('message.laborMange.time')}}
            </td>
            <td colspan="3" style="width: 30%">
              <div v-if="operateType != 3">
                <el-date-picker
                  v-model="dialogForm.violationTime"
                  type="date"
                  value-format="yyyy-MM-dd"
                  :placeholder="$t('message.laborMange.pleaseChoose')"
                >
                </el-date-picker>
              </div>
              <div v-else>{{ dialogForm.violationTime }}</div>
            </td>
          </tr>
          <tr colspan="10">
            <td colspan="2">
              {{
                dialogForm.fineType == 1
                  ? $t('message.laborMange.award')
                  : dialogForm.fineType == 2
                  ? $t('message.laborMange.withhold')
                  : $t('message.laborMange.fine')
              }}{{$t('message.laborMange.content')}}
            </td>
            <td colspan="8">
              <div v-if="operateType != 3">
                <el-input
                  type="textarea"
                  :placeholder="$t('message.laborMange.placeholder2')"
                  :rows="14"
                  v-model="dialogForm.fineContent"
                >
                </el-input>
              </div>
              <div v-else style="text-align: left">
                <pre style="min-height: 200px">{{
                  dialogForm.fineContent
                }}</pre>
              </div>
            </td>
          </tr>
          <tr colspan="10">
            <td colspan="2">
              {{
                dialogForm.fineType == 1
                   ? $t('message.laborMange.award')
                  : dialogForm.fineType == 2
                  ? $t('message.laborMange.withhold')
                  : $t('message.laborMange.fine')
              }}{{$t('message.laborMange.money')}}
            </td>
            <td colspan="8">
              <div class="flex">
                <div style="width: 40%; justify-content: center" class="flex">
                  <span>{{$t('message.laborMange.lowerCase')}}：</span>
                  <el-input
                    v-if="operateType != 3"
                    style="width: 50%"
                    :placeholder="$t('message.laborMange.placeholder2')"
                    maxlength="10"
                    @input="transformFn"
                    v-model="dialogForm.finePrice"
                    type="number"
                    oninput="if(value.length>12)value=value.slice(0,12)"
                  >
                  </el-input>
                  <span v-else>{{ dialogForm.finePrice }}</span>
                </div>
                <div style="width: 60%; justify-content: center" class="flex">
                  <span>{{$t('message.laborMange.capital')}}：</span>
                  <span>{{ amountInWords }}</span>
                </div>
              </div>
            </td>
          </tr>
          <tr colspan="10" style="height: 80px">
            <td colspan="2">{{$t('message.laborMange.MSS')}}</td>
            <td colspan="8"></td>
          </tr>
          <tr colspan="10" style="height: 80px">
            <td colspan="2">{{$t('message.laborMange.executive')}}</td>
            <td colspan="8"></td>
          </tr>
          <tr colspan="10" style="height: 80px" v-if="showWrap">
            <td colspan="2">{{$t('message.laborMange.uploadAttachment')}}</td>
            <td colspan="8" style="text-align: left">
              <div style="width: 500px">
                <el-upload
                  v-if="operateType != 3"
                  class="upload-demo"
                  :action="uploadUrl"
                  :on-remove="handleRemove"
                  :on-success="handleSuccess"
                  :on-error="handleError"
                  :on-preview="handlePreview"
                  :before-upload="handleBeforeUpload"
                  name="files"
                  :file-list="fileList"
                  style="width: 100%"
                  limit="3"
                >
                  <el-button size="small" type="primary">{{
                    $t("message.laborMange.clickOnTheUpload")
                  }}</el-button>
                </el-upload>
                <div v-else>
                  <div
                    v-for="(item, index) in fileList"
                    :key="index"
                    class="affix"
                    @click="handlePreview(item, 3)"
                  >
                    {{ item.name }}
                  </div>
                </div>
              </div>
            </td>
          </tr>
        </table>

        <div style="margin-top: 20px">
          <div>{{$t("message.laborMange.infuse")}}：</div>
          <div>1.{{$t("message.laborMange.printHint1")}} </div>
          <div>
            2.
            {{$t("message.laborMange.printHint2")}}
          </div>
          <div>
            {{$t("message.laborMange.printHint3")}}
          </div>
        </div>

        <!-- 回显打印附件 -->
        <div
          v-show="!showWrap && fileList.length > 0"
          style="page-break-after: always"
          v-for="(item, index) in fileList"
          :key="index"
        >
          <img :src="fileUrl + item.url" style="width: 100%" class="printImg" />
        </div>

        <div class="dialog-footer" v-if="showWrap">
          <el-button
            class="cancleBtn"
            @click="dialogVisible = false"
            icon="el-icon-circle-close"
            size="medium"
            >{{$t("message.laborMange.cancel")}}
          </el-button>
          <el-button
            v-if="operateType != 3"
            type="primary"
            icon="el-icon-circle-check"
            @click="saveBtn"
            size="medium"
            >{{$t("message.laborMange.save")}}
          </el-button>
          <el-button
            v-else
            type="primary"
            icon="el-icon-circle-check"
            @click="printBtn"
            size="medium"
            >{{$t("message.laborMange.print")}}
          </el-button>
        </div>
      </div>
    </el-dialog>
    <el-dialog :modal-append-to-body="false" :visible.sync="dialogImg">
      <img
        width="100%"
        height="auto"
        :src="dialogImageUrl"
        @click="btn(3)"
        alt=""
      />
    </el-dialog>
  </div>
</template>

<script>
import {
  getFineRecordListApi,
  getEnterpriseInfoList,
  addFineRecordApi,
  editFineRecordApi,
  deleteFineRecordApi,
} from "@/assets/js/api/laborPerson.js";
export default {
  name: "penalize",
  data() {
    return {
      projectSn: "",
      projectName: "",
      uploadUrl: "",
      fileUrl: "",
      fineType: "", //数据类型 1奖励，2扣款，3罚款
      total: 0,
      pageNo: 1,
      pageSize: 10,
      tableData: [],

      //新增 || 编辑 || 详情
      dialogForm: {
        titleName: "",
        fineType: 1,
        enterpriseId: "",
        fineNo: "",
        finePrice: "",
        fineContent: "",
        violationNature: "",
        violationTime: "",
        fileUrl: "",
      },
      unitList: [], //被罚单位列表
      amountInWords: "", //大写金额

      operateType: 1, //类型
      dialogTitle: this.$t("message.laborMange.add"),
      dialogVisible: false,
      workerInfo: {},
      fileList: [], //附件列表
      showWrap: true,
      dialogImg: false,
      dialogImageUrl: "",
    };
  },
  created() {
    this.projectSn = this.$store.state.projectSn;
    this.projectName = this.$store.state.currentProDetail.projectName;
    this.uploadUrl = 'http://192.168.34.221:8079/upload/image';
    console.log(this.$store.state,'文件服务')
    this.fileUrl = this.$store.state.FILEURL;
    this.selectData();
  },

  methods: {
    //请求列表数据
    selectData() {
      let data = {
        fineType: this.fineType,
        pageNo: this.pageNo,
        pageSize: this.pageSize,
        projectSn: this.projectSn,
      };
      getFineRecordListApi(data).then((res) => {
        if (res.code == 200) {
          this.tableData = res.result.records;
          this.total = res.result.total;
        } else {
          this.$message.error(res.message);
        }
      });
    },

    //获取处罚单位列表
    getUnitList() {
      let data = {
        projectSn: this.projectSn,
      };
      getEnterpriseInfoList(data).then((res) => {
        if (res.code == 200) {
          this.unitList = res.result;
        } else {
          this.$message.error(res.message);
        }
      });
    },

    //新增按钮
    addTicket() {
      this.dialogForm = {
        titleName: "",
        fineType: 1,
        enterpriseId: "",
        fineNo: "",
        finePrice: "",
        fineContent: "",
        violationNature: "",
        violationTime: "",
        fileUrl: "",
      };
      this.fileList = [];
      this.amountInWords = "";
      this.dialogVisible = true;
      this.operateType = 1;
      this.dialogTitle = this.$t("message.laborMange.add");
      this.getUnitList();
    },

    //编辑按钮
    editBtn(val) {
      this.fileList = [];
      this.dialogForm = {
        titleName: val.titleName,
        fineType: val.fineType,
        enterpriseId: val.enterpriseId,
        fineNo: val.fineNo,
        finePrice: val.finePrice,
        fineContent: val.fineContent,
        violationNature: val.violationNature,
        violationTime: val.violationTime,
        fileUrl: val.fileUrl,
        id: val.id,
      };
      if (val.finePrice) {
        this.transformFn(val.finePrice); //转大小写
      }
      if (val.fileUrl) {
        this.fileList = JSON.parse(val.fileUrl);
      }
      this.dialogVisible = true;
      this.operateType = 2;
      this.dialogTitle = this.$t("message.laborMange.edit");
      this.getUnitList();
    },

    //详情按钮
    detailBtn(val) {
      this.fileList = [];
      this.dialogForm = val;
      if (val.finePrice) {
        this.transformFn(val.finePrice); //转大小写
      }
      if (val.fileUrl) {
        this.fileList = JSON.parse(val.fileUrl);
      }
      this.dialogVisible = true;
      this.operateType = 3;
      this.dialogTitle = this.$t("message.laborMange.details");
    },

    //删除按钮
    deleteBtn(val) {
      this.$confirm(this.$t("message.laborMange.deleteHint"), this.$t("message.laborMange.hint"), {
        confirmButtonText: this.$t("message.laborMange.confirm"),
        cancelButtonText: this.$t("message.laborMange.cancel"),
        type: "warning",
      })
        .then(() => {
          let data = {
            id: val.id,
          };
          deleteFineRecordApi(data).then((res) => {
            if (res.code == 200) {
              this.$message({
                type: "success",
                message: this.$t("message.laborMange.deleteSuccess"),
              });
              this.selectData();
            } else {
              this.$message({
                type: "error",
                message: res.message,
              });
            }
          });
        })
        .catch(() => {
          // this.$message({
          //   type: "info",
          //   message: "已取消删除",
          // });
        });
    },

    //切换每页显示数量
    handleSizeChange(val) {
      // console.log(val)
      this.pageSize = val;
      this.selectData();
    },
    //切换分页
    handleCurrentChange(val) {
      this.pageNo = val;
      this.selectData();
    },

    //小写转大写
    transformFn(number) {
      if (!/^(0|[1-9]\d*)(\.\d+)?$/.test(number)) return this.amountInWords = null;
      var ret = "";
      if (number != "" && number != null && number != "0") {
        var unit = this.$t("message.laborMange.moneyUnit"),
          str = "";
        number += "00";
        var point = number.indexOf(".");
        if (point >= 0) {
          number = number.substring(0, point) + number.substr(point + 1, 2);
        }
        unit = unit.substr(unit.length - number.length);
        for (var i = 0; i < number.length; i++) {
          str +=
            this.$t("message.laborMange.moneyUpperCase").charAt(number.charAt(i)) + unit.charAt(i);
        }
        ret =
          str
            .replace(/零(仟|佰|拾|角)/g, "零")
            .replace(/(零)+/g, "零")
            .replace(/零(万|亿|元)/g, "$1")
            .replace(/(亿)万|(拾)/g, "$1$2")
            .replace(/^元零?|零分/g, "")
            .replace(/元$/g, "元") + "整";
      }
      this.amountInWords = ret;
      // console.log('number',number)
    },

    //上传之前
    handleBeforeUpload(file) {
      // if (
      //   file.type != "image/jpeg" ||
      //   file.type != "image/jpg" ||
      //   file.type != "image/png" ||
      //   file.type != "image/webp"
      // ) {
      //   this.$message.error(this.$t("message.laborMange.uploadedError"));
      //   return false;
      // }
    },
    //删除附件
    handleRemove(file, fileList) {
      this.fileList = fileList;
    },
    //上传成功
    handleSuccess(response, file, fileList) {
      this.fileList = fileList;
    },
    //上传失败
    handleError(error) {
      console.log(error);
    },

    // 点击附件
    handlePreview(file) {
      this.dialogImg = true;
      //详情
      if (file.url) {
        this.dialogImageUrl = this.fileUrl + file.url;
      } else 
      {
        this.dialogImageUrl = this.fileUrl + file.response.data[0].imageUrl;
      }
    },

    //保存按钮
    saveBtn() {
      if (this.dialogForm.titleName == "") {
        this.$message.error(this.$t("message.laborMange.placeholder2")+this.$t("message.laborMange.headline"));
        return;
      }
      if (this.dialogForm.fineNo == "") {
        this.$message.error(this.$t("message.laborMange.placeholder2")+this.$t("message.laborMange.serialNumber"));
        return;
      }
      if (this.dialogForm.enterpriseId == "") {
        let message = `${this.$t("message.laborMange.pleaseChoose")}${
          this.dialogForm.fineType == 1
            ? this.$t("message.laborMange.award")
            : this.dialogForm.fineType == 2
            ? this.$t("message.laborMange.withhold")
            : this.$t("message.laborMange.fine")
        }${this.$t("message.laborMange.unit")}`;
        this.$message.error(message);
        return;
      }

      //获取附件地址
      if (this.fileList.length > 0) {
        let urlArr = [];
        this.fileList.forEach((element, index) => {
          let url = {
            url: element.response
              ? element.response.data[0].filename
              : element.url,
            name: element.name,
          };
          urlArr.push(url);
        });
        this.dialogForm.fileUrl = JSON.stringify(urlArr);
      }
      let data = JSON.parse(JSON.stringify(this.dialogForm));

      data.projectSn = this.projectSn;
      //新增
      if (this.operateType == 1) {
        addFineRecordApi(data).then((res) => {
          if (res.code == 200) {
            this.$message.success(res.message);
            this.dialogVisible = false;
            this.pageNo = 1;
            this.pageSize = 10;
            this.selectData();
          } else {
            this.$message.error(res.message);
          }
        });
      } else {
        //编辑
        editFineRecordApi(data).then((res) => {
          if (res.code == 200) {
            this.$message.success(res.message);
            this.dialogVisible = false;
            this.pageNo = 1;
            this.pageSize = 10;
            this.selectData();
          } else {
            this.$message.error(res.message);
          }
        });
      }
    },

    //打印按钮
    printBtn() {
      this.showWrap = false;
      setTimeout(() => {
        let printDemo = document.getElementById("printDemo").innerHTML;
        let printImg = document.getElementsByClassName("printImg");
        window.document.body.innerHTML = printDemo;
        window.document.body.style.cssText = "height:auto"; //设置自适应高度 //不然只打印一页
        //有附件时
        if (printImg.length > 0) {
          //图片加载完成再打印
          printImg[printImg.length - 1].onload = function () {
            window.print();
            window.location.reload();
          };
        } else {
          //没有图片直接打印
          window.print();
          window.location.reload();
        }
      }, 100);
    },
  },
};
</script>

<style lang="less" scoped>
body {
  height: 100%;
}
.newTable {
  width: 100%;
  height: 100%;
  margin-top: 6px;
}
.flex {
  display: flex;
  align-items: center;
}
span {
  font-size: 16px;
}
h2,
h3 {
  text-align: center;
}
h2 {
  margin-top: 0;
}
table tr th,
table tr td {
  border: 1px solid;
  padding: 10px;
}
table {
  text-align: center;
  border-collapse: collapse;
}

.affix {
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
  margin: 10px;
  cursor: pointer;
}
</style>
