<template>
  <el-row>
    <el-col :span="24">
      <el-form
        ref="ruleForm"
        :model="ruleForm"
        :rules="feedbacksThis"
        label-width="130px"
        class="demo-ruleForm"
      >
        <el-row :gutter="10">
          <el-col :span="24">
            <el-form-item label="回执照片" prop="image" class="activity-upload">
              <div class="img-list-main clearfix">
                <div
                  class="img-item"
                  :class="{}"
                  v-for="(item, index) in ruleForm.image"
                  :key="item.image + index"
                >
                  <img v-viewer :src="item.image" class="avatar" />
                  <i
                    class="el-icon-close"
                    @click="closeImg(index, item.id)"
                  ></i>
                </div>
                <div
                  class="btnupload"
                  v-if="ruleForm.image.length < 101"
                  style="position: relative"
                  @click="open"
                >
                  <i class="el-icon-plus avatar-uploader-icon"></i>
                  <!-- ,.gif -->
                  <Upload
                    class="Upload"
                    :accept="'.jpg,.png,.bmp,.jpeg'"
                    :multiple="true"
                    :uploadcondition="beforeAvatarUpload"
                    @UploadErrorEvent="UploadErrorEvent"
                    @UploadSuccessEvent="UploadSuccessEvent"
                  ></Upload>
                </div>
              </div>
              <div class="txt-tips fl">
                <p>
                  <span sty>大小：小于1M；</span><span>尺寸：100*100；</span
                  ><span>类型：jpg.png.bmp.jpeg</span>
                </p>
              </div>
            </el-form-item>
            <el-form-item label="回执时间" prop="paytime">
              <el-date-picker
                v-model="ruleForm.paytime"
                type="datetime"
                :picker-options="pickerOptions"
                value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="选择回执时间"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-col>
    <el-col :span="24" style="text-align: right">
      <el-button type="primary" @click="submitForm">保 存 </el-button>
    </el-col>
  </el-row>
</template>
<script>
import asyncRequest from "@/apis/service/purchase/orderRecord";
import Upload from "@/components/Upload";
import resToken from "@/mixins/resToken";
export default {
  name: "orderRecord",
  props: ["id", "newTime", "payNo", "dstatus", "companyNo"],
  components: {
    Upload,
  },
  mixins: [resToken],
  data() {
    return {
      pickerOptions: {
        disabledDate: (time) => {
          if (time) {
            return time.getTime() >= new Date().valueOf();
          }
        },
      },
      image: [],
      loading: false,
      show: false,
      ruleForm: {
        sid: this.id,
        image: [],
        paytime: "",
      },
      feedbacksThis: this.feedbacks,
      feedbacks: {
        image: [
          {
            required: true,
            message: "请选择发票照片",
            trigger: "change",
          },
        ],
        paytime: [
          {
            required: true,
            message: "请选择回执时间",
            trigger: "change",
          },
        ],
      },
    };
  },

  watch: {
    newTime: function (old, val) {
      if (old !== val) {
        this.initForm();
      }
    },
  },
  mounted() {
    this.initForm();
  },
  methods: {
    transformTime(tTime) {
      // console.log(tTime);
      let time = new Date(tTime);
      // console.log(time);
      let y = this.setNum(time.getFullYear());
      let M = this.setNum(time.getMonth() + 1);
      let d = this.setNum(time.getDate());
      let H = this.setNum(time.getHours());
      let m = this.setNum(time.getMinutes());
      let s = this.setNum(time.getSeconds());
      return `${y}-${M}-${d} ${H}:${m}:${s}`;
    },
    setNum(num) {
      return num < 10 ? `0${num}` : num + "";
    },
    open() {
      this.show = true;
    },
    async initForm() {
      this.loading = true;
      console.log(this.dstatus);
      this.feedbacksThis = this.feedbacks;
      await this.resetForm();
      this.loading = false;
    },

    async resetForm() {
      // 重置
      await this.$nextTick(() => {
        if (this.$refs.ruleForm) {
          this.$refs.ruleForm.resetFields();
          this.$refs.ruleForm.clearValidate();
          this.ruleForm = {
            sid: this.id,
            image: [],
            paytime: new Date(),
          };
        }
      });
    },
    async submitForm() {
      await this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          this.loading = true;

          const obj = JSON.parse(JSON.stringify(this.ruleForm));
          let arr = [];
          obj.image.forEach((v1) => {
            arr.push(v1.image);
          });
          obj.image = arr.join(",");
          obj.status = "4";
          obj.sid = this.id;
          obj.paytime = this.transformTime(obj.paytime);
          // console.log(obj);
          // console.log(this.ruleForm);
          // return;
          let res = await asyncRequest.paymentexam(obj);
          if (res && res.code === 0) {
            const title = "回执上传成功！";
            this.$notify.success({
              title,
              message: "",
            });
            this.showModelThis = false;
            // 刷新
            this.$emit("refreshAll");
          } else if (res && res.code >= 100 && res.code <= 104) {
            await this.logout();
          } else {
            this.$message.warning(res.message);
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    async closeImg(index, id) {
      if (id) {
        this.loading = true;
        let res = await asyncRequest.invoicedel({ id: id });
        if (res && res.code === 0) {
          this.ruleForm.image.splice(index, 1);
          this.$refs.ruleForm.validateField("image");
        } else if (res && res.code >= 100 && res.code <= 104) {
          await this.logout();
        } else {
          this.$message.warning(res.message);
        }
        this.loading = false;
      } else {
        this.ruleForm.image.splice(index, 1);
        this.$refs.ruleForm.validateField("image");
      }
    },
    //图片上传失败
    UploadErrorEvent() {
      this.$message.error("图片上传失败!");
      this.$refs.ruleForm.validateField("image");
    },
    //图片上传成功
    UploadSuccessEvent(data) {
      if (data.url !== "break") {
        const { url } = data.url;
        this.ruleForm.image.push({ id: "", image: url });
        this.$message.success("图片上传成功!");
        this.$refs.ruleForm.validateField("image");
      }
    },
    //判断图片规格
    beforeAvatarUpload(file) {
      console.log(file);
      let isJPG = false;
      // ||
      //   file.type === "image/gif"
      if (
        file.type === "image/jpg" ||
        file.type === "image/png" ||
        file.type === "image/bmp" ||
        file.type === "image/jpeg"
      ) {
        isJPG = true;
      }
      const isLt2M = file.size / 1024 / 1024 < 1;
      if (!isJPG) {
        this.$message.error("图片格式不正确！");
      }
      if (!isLt2M) {
        this.$message.error("图片大小不能超过 1MB!");
      }
      return isJPG && isLt2M;
    },
  },
};
</script>

   <style lang="scss" scoped>
.orderRecord {
  .setWidth {
    width: 100% !important;
    // display: flex;
    // display: block !important;
    // .el-input__inner {
    //   display: flex;
    //   width: 1000px !important;
    //   display: block !important;
    // }
  }
  .activity-upload {
    position: relative;
    .img-list-main {
      position: relative;
      width: auto;
      // border-left: 1px solid rgb(220, 223, 230);
      .img-item {
        float: left;
        width: 202px;
        height: 167px;
        border: 1px solid rgb(220, 223, 230);
        // border-left: 0;
        position: relative;
        img {
          display: inline-block;
          width: 100%;
          height: 100%;
        }
        i {
          position: absolute;
          right: 6px;
          font-size: 16px;
          top: 6px;
          z-index: 2;
          color: #909399;
          &:hover {
            cursor: pointer;
            color: rgb(56, 193, 231);
          }
        }
      }
    }
    .btnupload {
      float: left;
      border: 1px solid rgb(220, 223, 230);
      // border-left: 0;
      box-sizing: border-box;
      width: 200px;
      height: 165px;
      line-height: 165px;
      text-align: center;
    }
    .Upload {
      width: 200px;
      height: 165px;
      line-height: 165px;
      text-align: center;
      position: absolute;
      line-height: 0px;
      top: 0;
      left: 0;
      z-index: 2;
      line-height: 165px;
    }
    .fileUp {
      vertical-align: top;
    }
    .avatar {
      width: 200px;
      height: 165px;
      line-height: 165px;
      text-align: center;
    }
    .avatar-uploader .el-upload:hover {
      border-color: #409eff;
    }
    .avatar-uploader-icon {
      font-size: 33px;
      color: #8c939d;
      width: 50px;
      height: 50px;
      line-height: 50px;
      text-align: center;
    }
    .avatar {
      width: 100%;
      height: 100%;
      display: block;
    }
    .txt-tips {
      display: inline-block;
      font-size: 13px;
      color: #606266;
      padding: 15px 0 0 15px;
      p {
        margin: 0;
        line-height: 30px;
        span {
          padding: 0 15px 0 0;
        }
      }
    }
    .avatar-uploader .el-upload {
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
    }
  }
}
</style>
