<!-- 验收弹窗 -->
<template>
  <el-dialog
    title="验收"
    :visible.sync="visible"
    width="650px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    @close="handleDialogClose"
    custom-class="check-dialog"
  >
    <!-- 添加隐藏的预览组件 -->
    <el-image
      style="display: none"
      ref="previewImage"
      :src="previewUrl"
      :preview-src-list="previewSrcList"
    />
    <el-form ref="form" :model="form" :rules="rules" label-width="120px">
      <el-form-item label="服务人员" prop="serviceStaffId">
        <el-select
          v-model="form.serviceStaffId"
          placeholder="请选择服务人员"
          style="width: 100%"
          filterable
        >
          <el-option
            v-for="item in installerOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="客户联系人" prop="customContact">
        <el-select
          v-model="form.customContact"
          placeholder="请选择或输入联系人"
          style="width: 100%"
          filterable
          allow-create
          default-first-option
          clearable
          @change="handleContactChange"
        >
          <el-option
            v-for="item in customerContactOptions"
            :key="item.id"
            :label="item.contactName"
            :value="item.id"
          >
            <span>{{ item.contactName }}</span>
            <span style="float: right; color: #8492a6; font-size: 13px">
              {{ item.telephone || "无电话" }}
            </span>
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="联系人电话" prop="telephone">
        <el-input
          v-model="form.telephone"
          placeholder="请输入联系人电话"
          style="width: 100%"
        />
      </el-form-item>

      <el-form-item label="验收日期" prop="checkDate">
        <el-date-picker
          v-model="form.checkDate"
          type="date"
          placeholder="选择验收日期"
          style="width: 100%"
        />
      </el-form-item>

      <el-form-item label="验收单" prop="checkImage">
        <div class="upload-wrapper">
          <el-upload
            ref="upload"
            id="uploadPic"
            list-type="picture-card"
            class="uploadPic"
            :action="uploadImageUrl"
            :limit="3"
            :headers="headers"
            :file-list="fileList"
            :on-preview="handlePicPreview"
            :auto-upload="true"
            :on-change="handlePicChange"
            :on-success="handlePicSuccess"
            :on-remove="handlePicRemove"
            :on-exceed="handleExceed"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
          <div class="upload-tip">最多上传3张图片</div>
        </div>
      </el-form-item>
    </el-form>

    <div slot="footer" class="dialog-footer">
      <el-button
        type="primary"
        @click="handleSubmit"
        :loading="submitting"
        class="submit-btn"
        >确 定</el-button
      >
      <el-button @click="handleCancel" class="cancel-btn">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { getToken } from "@/utils/auth";

export default {
  name: "CheckDialog",
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    rowData: {
      type: Object,
      default: () => ({}),
    },
    installerOptions: {
      type: Array,
      default: () => [],
    },
    currentUser: {
      type: Object,
      default: () => ({}),
    },
    customerContactOptions: {
      type: Array,
      default: () => [],
    },
  },
  data() {
    return {
      submitting: false,
      form: {
        serviceStaffId: "",
        customContact: "",
        telephone: "",
        checkDate: this.formatDate(new Date()),
        checkImage: [],
      },
      rules: {
        serviceStaffId: [
          { required: true, message: "请选择服务人员", trigger: "change" },
        ],
        customContact: [
          { required: true, message: "请输入联系人", trigger: "blur" },
        ],
        telephone: [
          { required: true, message: "请输入联系人电话", trigger: "blur" },
          {
            pattern: /^1\d{10}$/,
            message: "请输入11位有效的手机号码",
            trigger: "blur",
          },
        ],
        checkDate: [
          { required: true, message: "请选择验收日期", trigger: "change" },
        ],
        checkImage: [
          { required: true, message: "请上传验收单", trigger: "change" },
        ],
      },
      uploadImageUrl: process.env.VUE_APP_BASE_API + "authdata/uploaderimage",
      headers: {
        optname: "insertcustompic",
        id: 1,
        token: getToken(),
      },
      fileList: [],
      previewUrl: "",
      previewSrcList: [],
    };
  },
  watch: {
    visible(val) {
      if (val) {
        this.initForm();
      }
    },
  },
  methods: {
    initForm() {
      this.form = {
        serviceStaffId: parseInt(this.currentUser.id),
        serviceStaffName: "",
        customContact: "",
        telephone: "",
        checkDate: this.formatDate(new Date()),
        checkImage: [],
      };
      this.fileList = [];
    },
    beforeUpload(file) {
      const isImage = file.type.startsWith("image/");
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isImage) {
        this.$message.error("只能上传图片文件!");
        return false;
      }
      if (!isLt2M) {
        this.$message.error("图片大小不能超过 2MB!");
        return false;
      }
      return true;
    },
    handlePicSuccess(response, file, fileList) {
      const id = response.execresult.LastInsertId;
      // 直接将新ID添加到数组中
      this.form.checkImage.push(id);

      if (file.raw) {
        file.url = window.URL.createObjectURL(file.raw);
      }
      this.fileList = fileList;
    },
    handlePicChange(file, fileList) {
      this.fileList = fileList;
      // 根据文件列表长度控制上传按钮显示
      const uploadBtn = this.$refs.upload.$el.querySelector(
        ".el-upload--picture-card"
      );
      if (uploadBtn) {
        uploadBtn.style.display =
          fileList.length >= 3 ? "none" : "inline-block";
      }
    },
    handlePicPreview(file) {
      const { url } = file;
      if (!url) return;

      this.previewUrl = url;
      this.previewSrcList = [url];

      // 手动触发预览
      const previewImage = this.$refs.previewImage;
      if (previewImage) {
        previewImage.showViewer = true;
      }
    },
    handlePicRemove(file, fileList) {
      this.fileList = fileList;
      // 从数组中移除被删除图片的ID
      if (file.response && file.response.execresult) {
        const removedId = file.response.execresult.LastInsertId;
        this.form.checkImage = this.form.checkImage.filter(
          (id) => id !== removedId
        );
      }

      if (fileList.length === 0) {
        this.form.checkImage = [];
      }

      // 删除后重新显示上传按钮
      const uploadBtn = this.$refs.upload.$el.querySelector(
        ".el-upload--picture-card"
      );
      if (uploadBtn) {
        uploadBtn.style.display = "inline-block";
      }
    },
    handleExceed(files, fileList) {
      this.$message.warning("最多只能上传3张图片");
    },
    handleSubmit() {
      const isNewContact = !this.customerContactOptions.some(
        (item) => item.id === this.form.customContact
      );

      this.$refs.form.validate(async (valid) => {
        if (valid) {
          this.submitting = true;
          try {
            // 检查是否是新增的联系人
            const isNewContact = !this.customerContactOptions.some(
              (item) => item.id === this.form.customContact
            );

            await this.$emit("confirm", {
              isNewContact: isNewContact,
              orderId: this.rowData.id,
              serviceStaffId: this.form.serviceStaffId,
              serviceStaffName:
                this.installerOptions.find(
                  (item) => item.value === this.form.serviceStaffId
                )?.label || "",
              customContact: this.form.customContact,
              telephone: this.form.telephone,
              checkDate: this.formatDate(this.form.checkDate),
              checkImage: this.form.checkImage,
            });
          } finally {
            this.submitting = false;
          }
        }
      });
    },
    handleCancel() {
      this.$emit("update:visible", false);
    },
    handleDialogClose() {
      this.$refs.form.resetFields();
      this.handleCancel();
    },
    formatDate(date) {
      if (!date) return "";
      const d = new Date(date);
      const year = d.getFullYear();
      const month = String(d.getMonth() + 1).padStart(2, "0");
      const day = String(d.getDate()).padStart(2, "0");
      return `${year}-${month}-${day}`;
    },
    handleContactChange(value) {
      if (value) {
        const selectedContact = this.customerContactOptions.find(
          (item) => item.id === value
        );
        if (selectedContact) {
          this.form.telephone = selectedContact.telephone || "";
        }
      } else {
        this.form.telephone = "";
      }
    },
  },
};
</script>

<style lang="scss">
.check-dialog {
  :deep(.el-dialog__body) {
    padding: 20px 20px 10px 20px;
  }

  .upload-wrapper {
    .uploadPic {
      :deep(.el-upload--picture-card) {
        width: 148px !important;
        height: 148px !important;
        line-height: 148px !important;
        margin: 0 8px 8px 0;
        transition: display 0.3s;
      }

      :deep(.el-upload-list--picture-card .el-upload-list__item) {
        width: 148px !important;
        height: 148px !important;
        margin: 0 8px 8px 0;
      }
    }

    .upload-tip {
      font-size: 12px;
      color: #909399;
      margin-top: 5px;
    }
  }

  .dialog-footer {
    text-align: right;
    padding-top: 10px;

    .submit-btn {
      padding: 9px 20px;
      font-size: 14px;
      border-radius: 4px;
      margin-left: 10px;
      transition: all 0.3s;

      &:hover {
        opacity: 0.8;
        transform: translateY(-1px);
      }

      &:active {
        transform: translateY(0);
      }
    }

    .cancel-btn {
      padding: 9px 20px;
      font-size: 14px;
      border-radius: 4px;
      transition: all 0.3s;
      border: 1px solid #dcdfe6;

      &:hover {
        color: #409eff;
        border-color: #c6e2ff;
        background-color: #ecf5ff;
        transform: translateY(-1px);
      }

      &:active {
        transform: translateY(0);
      }
    }
  }
}

// 添加全局样式以优化遮罩层
:deep(.v-modal) {
  opacity: 0.7 !important;
}

// 优化预览样式
.el-image-viewer__wrapper {
  .el-image-viewer__btn {
    color: #fff;

    i {
      color: #fff;
      font-size: 24px;
    }
  }
}
</style>
