<template>
  <el-dialog title="公积金信息" v-model="visible" width="90%" append-to-body draggable @close="close" class="dialog-form" :close-on-click-modal = "false">
    <!-- 功能按钮 -->
    <div style="padding: 8px 24px 16px 24px">
      <el-form size="small" label-width="120px" v-model="form">
        <el-row :gutter="30">
          <el-col :span="12">
            <el-form-item label="客户名称">
              <div>{{ form.companyName }}</div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属月份">
              <div>{{ form.year }}-{{ form.month }}</div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="服务状态">
              <el-select v-model="form.status" placeholder="请选择">
                <el-option v-for="item in selectStatus" :key="item.value" :value="item.value" :label="item.label" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-divider content-position="left">公积金人员信息</el-divider>
          <el-col :span="24" class="details-container">
            <!--操作按钮 开始-->
            <div class="details-head" style="margin-bottom: 15px;">
              <!-- <div class="title"><i class="fa fa-th-list" aria-hidden="true" /> 人员信息</div> -->
              <el-button type="primary" size="small" icon="Plus" @click="handleEmployeeCreate">
                新增</el-button>
              <el-button v-if="selections.length > 0" type="danger" size="small" icon="delete"
                @click="handleEmployeeBatchDelete">删除</el-button>

            </div>
            <div class="details-body">
              <div>
                <el-table ref="sourceTable" :data="form.housingFundConfirm.details" size="small" max-height="490px"
                  border show-summary :summary-method="getSummaries" highlight-current-row
                  header-row-class-name="list-header-row" row-class-name="list-row" class="salary-table"
                  @selection-change="handleCheckChange" @current-change="handleCurrentChange">
                  <el-table-column type="selection" width="50" align="center" />
                  <el-table-column type="index" label="序号" width="50" align="center" />
                  <el-table-column label="姓名" width="150" align="center">
                    <template #default="scope">
                      <div>
                        <el-input v-model="scope.row.employeeName" size="small" placeholder="姓名" style="width: 100%" />
                      </div>
                      <span style="
                          color: red;
                          position: absolute;
                          z-index: 10;
                          top: 4px;
                          right: 12px;
                        ">*</span>
                    </template>
                  </el-table-column>
                  <el-table-column label="电话号" width="150" align="center">
                    <template #default="scope">
                      <div>
                        <el-input v-model="scope.row.phone" size="small" placeholder="电话号码" style="width: 100%" />
                      </div>
                      <span style="
                          color: red;
                          position: absolute;
                          z-index: 10;
                          top: 4px;
                          right: 12px;
                        ">*</span>
                    </template>
                  </el-table-column>
                  <el-table-column label="身份证正面" width="120" align="center">
                    <template #default="scope">
                      <div>
                        <!-- <el-upload
                          action="#"
                          :http-request="
                            (params) =>
                              uploadIdImage(params, scope.row, 'idCardImage')
                          "
                          :with-credentials="true"
                          :show-file-list="false"
                        >
                          <template v-if="scope.row.idCardImage === ''">
                            <div class="el-upload__text" style="color: blue">
                              点击上传
                            </div>
                        
                          </template>
                          <img
                            v-else
                            class="img"
                            :src="baseUrl + '/' + scope.row.idCardImage"
                            alt=""
                          />
                        </el-upload>  -->
                        <div>
                          <div id="preview" v-on:paste="handlePaste($event,scope.row,'idCardImage')"
                            v-if="scope.row.idCardImage === ''">
                            <span>将图片粘贴至此</span>
                          </div>
                          <div class="image-container" v-else>
                            <el-image class="img" :src="baseUrl + scope.row.idCardImage" alt=""
                              preview-teleported="true" fit="contain" :preview-src-list="srcList"
                              @click="vbs(baseUrl + scope.row.idCardImage)" />
                            <!-- 删除按钮 -->
                            <el-icon  v-if="scope.row.idCardImage !== ''" @click="scope.row.idCardImage = ''"
                              class="delete-button">
                              <Delete />
                            </el-icon>
                          </div>
                        </div>

                      </div>
                      <span style="
                          color: red;
                          position: absolute;
                          z-index: 10;
                          top: 4px;
                          right: 12px;
                        ">*</span>
                    </template>
                  </el-table-column>
                  <el-table-column label="身份证反面" width="120" align="center">
                    <template #default="scope">
                      <div>
                        <!-- <el-upload
                          action="#"
                          :http-request="
                            (params) =>
                              uploadIdImage(
                                params,
                                scope.row,
                                'idCardImageBack'
                              )
                          "
                          :with-credentials="true"
                          :show-file-list="false"
                        >
                          <template v-if="scope.row.idCardImageBack === ''">
                            <div class="el-upload__text" style="color: blue">
                              点击上传
                            </div>
                          </template>
                          <img
                            v-else
                            class="img"
                            :src="baseUrl + '/' + scope.row.idCardImageBack"
                            alt=""
                          />
                        </el-upload> -->
                        <div>
                          <div id="preview2" v-on:paste="handlePaste($event,scope.row,'idCardImageBack')"
                            v-if="scope.row.idCardImageBack === ''">
                            <span>将图片粘贴至此</span>
                          </div>

                          <div class="image-container" v-else>
                            <el-image class="img" :src="baseUrl + scope.row.idCardImageBack" alt=""
                              preview-teleported="true" fit="contain" :preview-src-list="srcListback"
                              @click="vbsBack(baseUrl + scope.row.idCardImageBack)" />
                            <!-- 删除按钮 -->
                            <el-icon  v-if="scope.row.idCardImageBack !== ''"
                              @click="scope.row.idCardImageBack = ''" class="delete-button">
                              <Delete />
                            </el-icon>
                          </div>
                        </div>
                      </div>
                      <span style="
                          color: red;
                          position: absolute;
                          z-index: 10;
                          top: 4px;
                          right: 12px;
                        ">*</span>
                    </template>
                  </el-table-column>
                  <el-table-column label="基数" width="140" align="center">
                    <template #default="scope">
                      <div>
                        <el-input-number v-model="scope.row.cardinalNumber" :precision="2" :controls="false"
                          size="small" placeholder="基数" @blur="onblur(scope.row, 'cardinalNumber')" />
                      </div>
                      <span style="
                          color: red;
                          position: absolute;
                          z-index: 10;
                          top: 4px;
                          right: 12px;
                        ">*</span>
                    </template>
                  </el-table-column>
                  <el-table-column label="比例" width="160" align="center">
                    <template #default="scope">
                      <div>
                        <el-input v-model="scope.row.ratio" size="small" @blur="onblur(scope.row, 'ratio')">
                          <template #suffix>
                            <i style="
                                font-style: normal;
                                margin-right: 0px;
                                display: inline-block;
                                line-height: 20px;
                              ">%</i>
                          </template>
                        </el-input>
                      </div>
                      <span style="
                          color: red;
                          position: absolute;
                          z-index: 10;
                          top: 4px;
                          right: 12px;
                        ">*</span>
                    </template>
                  </el-table-column>
                  <!-- <el-table-column label="签名" width="100" header-align="center" required>
                  </el-table-column> -->
                  <el-table-column label="备注" header-align="center">
                    <template #default="scope">
                      <div>
                        <el-input v-model="scope.row.remark" size="small" placeholder="备注" />
                      </div>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </div>
          </el-col>
          <el-col :span="24" style="margin-top: 15px;">
            <el-form-item label="备注">
              <el-input maxlength="200" show-word-limit v-model.trim="form.housingFundConfirm.content" type="textarea"
                rows="2" />
            </el-form-item>
          </el-col>
          <el-divider content-position="left">公积金申报信息</el-divider>
          <el-col :span="12">
            <el-form-item label="单位缴纳：">
              <el-input-number v-model="form.housingFundDeclare.unitAmount" size="small" placeholder="单位缴纳"
                :precision="2" :controls="false" style="width: 100%" @change="amountChangeHandler" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="个人缴纳：">
              <el-input-number v-model="form.housingFundDeclare.individualAmount" size="small" placeholder="个人缴纳"
                :precision="2" :controls="false" style="width: 100%" @change="amountChangeHandler" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="合计：">
              <div>{{ rowNum(form.housingFundDeclare.amount) }}</div>
              <!-- <el-input-number
                v-model="form.housingFundDeclare.amount"
                size="small"
                placeholder="个人缴纳"
                :precision="2"
                :controls="false"
                style="width: 100%"
              /> -->
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-divider />
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input v-model.trim="form.housingFundDeclare.content" maxlength="200" show-word-limit type="textarea"
                rows="2" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="凭证" required>
              <el-upload action="#" :http-request="upload" :with-credentials="true" :show-file-list="false" multiple>
                <el-button size="small" type="primary" icon="Upload">点击上传</el-button>
              </el-upload>
              <el-table ref="dbTable" :data="form.housingFundDeclare.evidenceFiles" size="small" border
                header-row-class-name="list-header-row" row-class-name="list-row" style="margin-top: 15px;">
                <el-table-column label="文件名" prop="originalFileName" align="center" show-overflow-tooltip>
                  <template #default="scope">
                    <el-button size="small" type="text" @click="openFile(scope.row)">{{
                      scope.row.originalFileName == ""
                      ? "打开文件"
                      : scope.row.originalFileName
                      }}</el-button>
                  </template>
                </el-table-column>
                <!-- <el-table-column
                  label="文件类型"
                  width="80"
                  prop="fileType"
                  align="center"
                /> -->
                <el-table-column label="操作" width="80" prop="fileType" align="center">
                  <template #default="scope">
                    <el-button size="small" link type="danger"
                      @click="handleDel(scope.row, scope.$index)">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div class="form-btns-container" style="height: 40px">
      <el-button size="small" style="float: right" @click="close" icon="close">取消</el-button>
      <el-button type="primary" size="small" icon="Finished" style="float: right; margin-left: 12px; margin-right: 12px"
        @click="handleSave">保存</el-button>
    </div>
    <!-- <feedback-dialog ref="feedbackDialogView" :parent="this" />
    <print-dialog ref="printDialog" :parent="this" /> -->
  </el-dialog>
</template>
<script setup>
  import {
    getDetail,
    saveDetail,
    updateDetail,
  } from "@/api/business/crm/serviceWorkOrder";
  import { rowNum, numberToCurrencyNo } from "@/utils/index";
  import { uploadFile } from "@/api/tool/file";
  import { ref } from "vue";
  import zTool from '@/utils/zTool'
  const { proxy } = getCurrentInstance();
  const visible = ref(false);
  const baseUrl = import.meta.env.VITE_APP_BASE_API;

  const selections = ref([]);
  const currentSource = ref(null);

  const props = defineProps({
    getList: {
      type: Function,
      default: () => { },
    },
  });
  const selectStatus = ref([
    {
      label: "未开始",
      value: 0,
      color: "#fff",
    },
    {
      label: "进行中",
      value: 1,
      color: "#FFB836",
    },
    {
      label: "已完成",
      value: 3,
      color: "#2FCB81",
    },
  ]);
  const { getList } = toRefs(props);
  const total = ref(0);
  const tempFile = ref(null)
  const employeeEmptyData = {
    id: null,
    title: "",
    remark: "",
    employeeName: "",
    departmentName: "",
    idCardImage: "",
    idCardImageBack: "",
    idiograph: "",
    details: [],
    editStatus: true,
  };
  const srcList = ref([
    "https://elevator4s-oss.oss-cn-hangzhou.aliyuncs.com/2021/05/07/b632db6a837f46e0950670277fa9e5e5multipartFile.png"
  ]);
  const srcListback = ref([
    "https://elevator4s-oss.oss-cn-hangzhou.aliyuncs.com/2021/05/07/b632db6a837f46e0950670277fa9e5e5multipartFile.png"
  ]);
  const form = ref({});

  const emptyForm = {
    housingFundConfirm: {},
    housingFundDeclare: {},
  };

  function open(detail) {
    visible.value = true;
    form.value = { ...emptyForm, ...detail };
    loadData();
  }
  function vbs(val) {
    srcList.value = []
    srcList.value.push(val)
  }
  function vbsBack(val) {
    srcListback.value = []
    srcListback.value.push(val)
  }
  function loadData() {
    getDetail(form.value).then((res) => {
      form.value = { ...proxy.deepClone(emptyForm), ...res.data };
      computeTotal();
    });
  }

  function close() {
    visible.value = false;
    reset();
  }

  function reset() {
    form.value = proxy.deepClone(emptyForm);
  }

  function printSalary() { }
  function exportSalary() { }

  function handleCurrentChange(row) {
    currentSource.value = row;
  }

  function handleCheckChange(selection) {
    selections.value = selection.map((item) => item);
  }

  function handleSave() {
    proxy.$modal
      .confirm("确认保存么？")
      .then(() => {
        const saveValue = proxy.deepClone(form.value);
        saveDetail(saveValue).then((res) => {
          proxy.$modal.msgSuccess("保存成功");
          reset();
          close();
          getList.value();
        });
      })
      .catch((err) => {
        proxy.$modal.msg("取消保存");
      });
  }

  function getSummaries(param) {
    const { columns, data } = param;
    const sums = [];
    columns.forEach((column, index) => {
      if (index === 0) {
        sums[index] = "合计";
        return;
      } else if (index === 1) {
        sums[index] = "";
        return;
      }
      const values = data.map((item) => Number(item[column.property]));

      if (!values.every((value) => isNaN(value))) {
        sums[index] = values.reduce((prev, curr) => {
          const value = Number(curr);
          if (!isNaN(value)) {
            return (Number(prev) + Number(curr)).toFixed(2);
          } else {
            return Number(prev).toFixed(2);
          }
        }, 0);
      } else {
        sums[index] = "";
      }
    });
    return sums;
  }

  function handleEmployeeCreate() {
    // 此处必须进行深拷贝，否则添加的明细，将都指向了一个对象
    const _newSource = JSON.parse(JSON.stringify(employeeEmptyData));
    form.value.housingFundConfirm.details.push(_newSource);
    handleCurrentChange(_newSource);
  }

  function handleEmployeeBatchDelete() {
    proxy.$modal
      .confirm("确定删除?")
      .then(() => {
        form.value.housingFundConfirm.details =
          form.value.housingFundConfirm.details.filter(
            (item) => selections.value.indexOf(item) === -1
          );
      })
      .catch(() => {
        proxy.$modal.msg("已取消删除");
      });
  }

  function upload(param) {
    const formData = new FormData();
    formData.append("file", param.file);
    uploadFile(formData).then((res) => {
      if (res.code === 200) {
        const file = {};
        file.fileName = res.newFileName;
        file.url = res.url;
        file.originalFileName = res.originalFilename;
        file.fileUrl = res.fileName;
        form.value.housingFundDeclare.evidenceFiles.push(file);
      }
    });
  }

  function openFile(row) {
    window.open(`${baseUrl.value}${row.fileUrl}`);
  }

  function handleDel(row, index) {
    proxy.$modal
      .confirm("确定删除吗？")
      .then((_) => {
        form.value.housingFundDeclare.evidenceFiles.splice(index, 1);
      })
      .catch((_) => {
        proxy.$modal.msg("已取消删除");
      });
  }

  function computeTotal() {
    let totalSalay = 0;
    form.value.housingFundConfirm.details.forEach((l) => {
      totalSalay += l.actuallySalary == null ? 0 : l.actuallySalary;
    });
    form.value.housingFundConfirm.amount = totalSalay.toFixed(2);
  }

  function uploadIdImage(param, row, field) {
    const formData = new FormData();
    formData.append("file", param.file);
    uploadFile(formData).then((res) => {
      if (res.code === 200) {
        const file = {};
        file.fileType =
          res.newFileName.split(".")[res.newFileName.split(".").length - 1];
        if (file.fileType !== "png" && file.fileType !== "jpg") {
          proxy.$modal.msgError("文件类型错误,只能上传png,jpg格式");
          return;
        }
        file.fileName = res.newFileName;
        file.url = res.url;
        file.originalFileName = res.originalFilename;
        file.fileUrl = res.fileName;
        row[field] = file.fileUrl;
      }
    });
  }

  function amountChangeHandler() {
    let amount = 0;
    amount +=
      form.value.housingFundDeclare.unitAmount == null
        ? 0
        : form.value.housingFundDeclare.unitAmount;
    amount +=
      form.value.housingFundDeclare.individualAmount == null
        ? 0
        : form.value.housingFundDeclare.individualAmount;
    form.value.housingFundDeclare.amount = amount;
  }


  // 监听粘贴操作
  function handlePaste(event, row, field) {
    const items = (event.clipboardData || window.clipboardData).items;
    let file = null;
    if (!items || items.length === 0) {
      this.$message.error("当前浏览器不支持本地");
      return;
    }
    // 搜索剪切板items
    for (let i = 0; i < items.length; i++) {
      if (items[i].type.indexOf("image") !== -1) {
        file = items[i].getAsFile();
        break;
      }
    }
    if (!file) {
      this.$message.error("粘贴内容非图片");
      return;
    }
    zTool.addWatermark(file,"仅供公积金申报使用").then(watermarkedFile => {
      tempFile.value = watermarkedFile
      uploadIdImage2(tempFile, row, field)
    })
    // tempFile.value = file;
    // uploadIdImage2(tempFile, row, field)
  }

  function uploadIdImage2(tempFile, row, field) {
    const formData = new FormData();
    formData.append("file", tempFile.value);
    uploadFile(formData).then((res) => {
      if (res.code === 200) {
        const file = {};
        file.fileType =
          res.newFileName.split(".")[res.newFileName.split(".").length - 1];
        if (file.fileType !== "png" && file.fileType !== "jpg") {
          proxy.$modal.msgError("文件类型错误,只能上传png,jpg格式");
          return;
        }
        file.fileName = res.newFileName;
        file.url = res.url;
        file.originalFileName = res.originalFilename;
        file.fileUrl = res.fileName;
        row[field] = file.fileUrl;
      }
    });
  }


  // 暴露给父组件的方法
  defineExpose({
    open,
  });
</script>
<style scoped>
  .image-container {
    display: flex;
    /* 使用Flex布局 */
    align-items: center;
    /* 垂直居中 */
  }

  .delete-button {
    margin-left: 20px;
    cursor: pointer;
  }

  .img {
    width: 23px;
    height: 23px;
    display: flex;
    justify-content: center;
    align-items: center;
    margin-left: 20px;
  }

  ::v-deep(.el-upload) {
    display: flex;
    text-align: center;
    justify-content: center;
    cursor: pointer;
    outline: 0;
  }

  .required::after {
    content: "*";
    color: red;
  }
</style>
<style>
  .el-table .delete-row {
    background-color: rgb(251, 159, 173);
  }

  .el-table .add-row {
    background-color: rgb(184, 234, 147);
  }
</style>