<template>
  <view class="device-repair-page">
    <cu-custom :isBack="true">
      <template slot="content">
        <view class="nav-title">设备报修</view>
      </template>
    </cu-custom>
    <view class="form-board">
      <u-form
        ref="baseFormRef"
        :model="baseForm"
        labelWidth="162"
        :rules="rules"
        errorType="toast"
      >
        <view class="repaid-board">
          <view class="title">基本信息</view>
          <u-form-item label="设备ID" prop="device_id" required>
            <u-input
              v-model="baseForm.device_id"
              placeholder="设备ID"
              disabled
            ></u-input>
          </u-form-item>
          <u-form-item label="设备名称" prop="devName" required>
            <u-input
              v-model="baseForm.devName"
              placeholder="请输入设备名称"
              disabled
            ></u-input>
          </u-form-item>
          <u-form-item label="联系人" prop="user" required>
            <u-input
              v-model="baseForm.user"
              placeholder="请输入"
            ></u-input>
          </u-form-item>
          <u-form-item label="联系人电话" prop="userphone" required>
            <u-input
              v-model="baseForm.userphone"
              placeholder="请输入"
              type="number"
            ></u-input>
          </u-form-item>
          <u-form-item label="联系人地址" prop="addr" required>
            <u-input
              v-model="baseForm.addr"
              placeholder="请输入"
            ></u-input>
          </u-form-item>
        </view>
        <view class="repaid-board">
          <view class="title">报修详情</view>
          <u-input
            v-model="baseForm.errordesc"
            placeholder="请描述设备问题"
            type="textarea"
            :height="216"
            maxlength="140"
            show-word-limit
          ></u-input>

          <view class="upload-section">
            <view class="upload-title"
              >设备照片<text class="info">(最多4张)</text></view
            >
            <u-upload
              :file-list="fileList"
              :max-count="4"
              @on-choose-complete="onChooseComplete"
              @on-remove="onRemove"
              name="upload"
              :max-size="5 * 1024 * 1024"
              accept="image/*"
              :auto-upload="false"
              :show-progress="false"
            >
              <view slot="addBtn" class="add-btn">
                <u-icon name="plus" size="56" color="#909399"></u-icon>
              </view>
            </u-upload>
          </view>
        </view>
      </u-form>
    </view>

    <view class="footer-board">
      <u-button type="success" class="sub-btn" @click="submitForm"
        >确定</u-button
      >
    </view>
  </view>
</template>

<script>
import uInput from "../../../uview-ui/components/u-input/u-input.vue";
export default {
  components: { uInput },
  onLoad(options) {
    const deviceInfo = JSON.parse(decodeURIComponent(options.deviceInfo));
    console.log("deviceInfo:", deviceInfo);
    this.baseForm.device_id = deviceInfo.devBid
    this.baseForm.devName = deviceInfo.devName
  },
  data() {
    return {
      baseForm: {
        device_id: "",
        devName: "",
        user: "",
        userphone: "",
        addr: "",
        errordesc: "",
      },
      rules: {
        devName: [
          {
            required: true,
            message: "请输入设备名称",
            trigger: ["blur", "change"],
          },
        ],
        user: [
          {
            required: true,
            message: "请输入联系人",
            trigger: ["blur", "change"],
          },
        ],
        userphone: [
          {
            required: true,
            message: "请输入联系人电话",
            trigger: ["blur", "change"],
          },
          {
            pattern: /^1[3-9]\d{9}$/,
            message: "请输入正确的手机号",
            trigger: ["blur", "change"],
          },
        ],
        addr: [
          {
            required: true,
            message: "请输入联系人地址",
            trigger: ["blur", "change"],
          },
        ],
        errordesc: [
          {
            required: true,
            message: "请描述设备问题",
            trigger: ["blur", "change"],
          },
        ],
      },
      fileList: [],
    };
  },
  methods: {
    onChooseComplete(lists) {
      const newFiles = lists.filter(
        (item) => !this.fileList.some((f) => f.url === item.url)
      );
      newFiles.forEach((file) => {
        const item = {
          url: file.url,
          status: "uploading",
        };
        this.fileList.push(item);
        const index = this.fileList.length - 1;
        uni.uploadFile({
          url: "https://wx.hnyfwlw.com/api/api_gateway?method=base.bases.base_photo",
          filePath: file.url,
          name: "img_file",
          formData: {
            user: "test",
          },
          success: (uploadFileRes) => {
            const data = JSON.parse(uploadFileRes.data);
            if (data.data && data.data.src) {
              this.fileList[index].status = "success";
              this.fileList[index].src = data.data.src;
              this.$forceUpdate();
              console.log("上传成功，图片地址：", data.data.src);
            } else {
              this.fileList[index].status = "failed";
              uni.showToast({
                title: data.msg || "上传失败",
                icon: "none",
              });
            }
          },
          fail: (err) => {
            this.fileList[index].status = "failed";
            uni.showToast({
              title: "上传失败",
              icon: "none",
            });
            console.error("上传失败：", err);
          },
        });
      });
    },
    onRemove(index) {
      this.fileList.splice(index, 1);
    },
    submitForm() {
      const hasUploading = this.fileList.some((f) => f.status === "uploading");
      if (hasUploading) {
        uni.showToast({
          title: "请等待图片上传完成",
          icon: "none",
        });
        return;
      }
      const hasFailed = this.fileList.some((f) => f.status === "failed");
      if (hasFailed) {
        uni.showToast({
          title: "有图片上传失败，请重新上传",
          icon: "none",
        });
        return;
      }
      this.$refs.baseFormRef
        .validate()
        .then((res) => {
          const uploadedImages = this.fileList
            .filter((f) => f.status === "success" && f.src)
            .map((f) => f.src);
          const params = {
            ...this.baseForm,
            errorimg: uploadedImages,
          };
          console.log("提交参数：", params);
          // 
          this.$myRequest({
            url: "/api/api_gateway?method=after_sale.after_sale_manage.aftersale_apply",
            data: params,
          }).then(res => {
            console.log("aftersale_apply:", res);
            if(res){
              uni.showToast({
                  title: '提交成功',
                  duration: 2000,
              });
              setTimeout(()=>{
                uni.navigateBack({
                  delta:1
                })
              },1000)
            }else{
              uni.showToast({
                  title: '提交失败',
                  duration: 2000,
                icon:"none"
              });
            }
          })
        })
        .catch((errors) => {
          console.log("表单验证失败", errors);
        });
    },
  },
};
</script>

<style lang="scss">
.device-repair-page {
  background:
    linear-gradient(180deg, #ffffff00 0%, #f5f6fa 23.64%, #f5f6fa 100%),
    linear-gradient(102deg, #bfeadd 6.77%, #b8f1e7 40.15%, #b9eef5 84.02%);
  min-height: 100vh;
  padding: 0 32rpx;
  padding-top: 98rpx;
  padding-bottom: 200rpx;
}

.form-board {
  margin-top: 46rpx;
}
.repaid-board {
  background: #fff;
  border-radius: 16rpx;
  padding: 32rpx;
  margin-bottom: 24rpx;

  .title {
    color: #020305;
    font-size: 32rpx;
    font-weight: bold;
  }
}

.upload-section {
  padding: 20rpx 0;

  .upload-title {
    font-size: 28rpx;
    color: #303133;
    margin-bottom: 16rpx;
    .info {
      color: #999;
    }
  }

  .add-btn {
    background: #f1f4f8;
    width: 160rpx;
    height: 160rpx;
    border-radius: 12rpx;
    display: flex;
    justify-content: center;
    align-items: center;
  }
}

// 使所有输入框文本右对齐
::v-deep .uni-input-input,
::v-deep .uni-input-placeholder {
  text-align: right !important;
}
::v-deep .u-add-wrap {
  display: none !important;
}
::v-deep .u-input__textarea {
  background: #f1f4f8 !important;
  border-radius: 8rpx;
  margin-top: 24rpx;
  padding: 17rpx 24rpx !important;
}

.footer-board {
  border-top: 2rpx solid #e4e7ed;
  background: #fff;
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 164rpx;
  padding: 16rpx 32rpx 0 32rpx;

  .sub-btn {
    width: 100%;
    background: #0bbc58;
    border-radius: 16rpx;
  }
}
</style>
