<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 v-viewer class="img-list-main clearfix">
                <div
                  class="img-item"
                  :class="{ error: item.status === '4' || item.status === '2' }"
                  v-for="(item, index) in ruleForm.image"
                  :key="item.image + index"
                  @mouseenter="item.show = true"
                  @mouseout="item.show = false"
                >
                  <img
                    :src="item.image"
                    class="avatar"
                    :class="{
                      error: item.status === '4' || item.status === '2',
                    }"
                  />
                  <p class="img_name">{{ item.name }}</p>
                  <i
                    class="el-icon-close"
                    @click="closeImg(index, item.id)"
                  ></i>
                  <ul
                    @mouseenter="item.show = true"
                    @mouseout="item.show = false"
                    class="error-m"
                    :class="{ show: item.show, close: !item.show }"
                    v-if="item.status === '4' || item.status === '2'"
                  >
                    <li
                      @mouseenter="item.show = true"
                      @mouseout="item.show = false"
                      v-for="v in item.remark"
                      :key="v"
                    >
                      {{ v }}
                    </li>
                  </ul>
                </div>
                <div
                  class="btnupload"
                  v-if="ruleForm.image.length < 101"
                  style="position: relative"
                  @click="open"
                >
                  <i class="el-icon-plus avatar-uploader-icon"></i>
                  <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>大小：小于1MB；</span><span>尺寸：250*160；</span
                  ><span>类型：jpg.png.bmp.jpeg</span>
                </p>
              </div>
            </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 {
      image: [],
      loading: false,
      show: false,
      ruleForm: {
        sid: this.id,
        image: [],
      },
      feedbacksThis: this.feedbacks,
      feedbacks: {
        image: [
          {
            required: true,
            message: "请选择发票照片",
            trigger: "change",
          },
        ],
      },
    };
  },

  watch: {
    newTime: function (old, val) {
      if (old !== val) {
        this.initForm();
      }
    },
  },
  mounted() {
    this.initForm();
  },
  methods: {
    open() {
      this.show = true;
    },
    async initForm() {
      this.loading = true;
      // console.log(this.dstatus);
      this.feedbacksThis = this.feedbacks;
      await this.resetForm();
      await this.initData();
      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: [],
          };
        }
      });
    },
    async initData() {
      const res = await asyncRequest.invoiceinfo({ sid: this.id });
      if (res && res.code === 0 && res.data && res.data.invoice) {
        const data = res.data.invoice || [];
        let arr = [];
        if (data.length > 0) {
          data.forEach((v) => {
            let model = {
              id: v.id,
              image: v.image,
              status: v.status,
              name: v.name,
              remark: v.remark ? v.remark.split(";") : "",
              show: false,
            };
            arr.push(model);
          });
        }
        this.ruleForm = {
          sid: this.id,
          image: arr,
        };
        this.$refs.ruleForm.clearValidate();
      } else if (res && res.code >= 100 && res.code <= 104) {
        await this.logout();
      } else {
        this.$message.warning(res.message);
      }
    },
    async submitForm() {
      await this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          this.loading = true;
          const obj = JSON.parse(JSON.stringify(this.ruleForm));
          let isOk = true;
          console.log(obj.image);
          let arr = [];
          obj.image.forEach((v) => {
            if (v.status === "3" || v.status === "4") {
              isOk = false;
            }
            if (v.id === "") {
              let itemA = {
                url: v.image,
                name: v.name,
              };
              arr.push(itemA);
            }
          });
          if (!isOk) {
            this.$message.error("存在识别异常或审核失败图片！");
            return;
          }
          if (arr.length > 0) {
            obj.image = arr;
            let res = {};
            res = await asyncRequest.invoiceadd(obj);
            if (res && res.code === 0) {
              await this.invoicecheck();
            } else if (res && res.code >= 100 && res.code <= 104) {
              await this.logout();
            } else {
              this.$message.warning(res.message);
            }
          } else {
            await this.invoicecheck();
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },

    async invoicecheck() {
      let res = await asyncRequest.invoicecheck({ sid: this.id,type:1 });
      if (res && res.code === 0) {
        await this.invoiceSuccess();
      } else if (res && res.code >= 100 && res.code <= 104) {
        await this.logout();
      } else {
        this.$message.warning(res.message);
      }
      this.loading = false;
    },

    async invoiceSuccess() {
      const title = "发票上传成功！";
      this.$notify.success({
        title,
        message: "系统正在努力识别发票，请等待识别结果！",
      });
      this.showModelThis = false;
      // 刷新
      this.$emit("refreshAll");
    },

    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 && data.url && data.url !== "break") {
        const { url, name } = data.url;
        this.ruleForm.image.push({ id: "", image: url, name: name });
        this.$message.success("图片上传成功!");
        this.$refs.ruleForm.validateField("image");
      }
    },
    //判断图片规格
    beforeAvatarUpload(file) {
      let isJPG = false,
        isLt2M = false;
      if (file) {
        if (
          file.type === "image/jpg" ||
          file.type === "image/png" ||
          file.type === "image/bmp" ||
          file.type === "image/jpeg"
        ) {
          isJPG = true;
        }
        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;
      vertical-align: top;
      // border-left: 1px solid rgb(220, 223, 230);
      .img-item {
        vertical-align: top;
        float: left;
        width: 254px;
        height: 186px;
        position: relative;
        // background: chartreuse;
        border: 0;
        // border: 1px solid rgb(220, 223, 230);
        // border-left: 0;
        .img_name {
          height: 20px;
          line-height: 20px;
          text-align: center;
          font-size: 12px;
          width: 100%;
          display: inline-block;
          vertical-align: top;
          overflow: hidden;
          margin: -15px 0 0 0;
          // background: chartreuse;
          padding: 0;
        }

        &.error {
          .error-m {
            position: absolute;
            background: #f2f2f2;
            left: 0;
            top: 0;
            z-index: 20;
            width: 254px;
            height: 164px;
            line-height: 164px;
            text-align: left;
            display: flex;
            border: 1px solid #c03639;
            box-sizing: border-box;
            align-items: center;
            padding: 16px;
            box-sizing: border-box;

            li {
              width: 100%;
              padding: 5px 0;
              max-height: 160px;
              color: #c03639;
              text-align: center;
              box-sizing: border-box;
            }
            &.show {
              opacity: 1;
              transition: opacity 0.3s;
            }
            &.close {
              opacity: 0;
              transition: opacity 0.3s;
            }
          }
        }
        img {
          display: inline-block;
          width: 100%;
          height: 164px;
          border: 1px solid rgb(220, 223, 230);
          &.error {
            border: 1px solid #c03639;
          }
        }
        i {
          position: absolute;
          right: 6px;
          font-size: 16px;
          top: 6px;
          z-index: 30;
          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: 254px;
      height: 164px;
      line-height: 164px;
      text-align: center;
    }
    .Upload {
      width: 254px;
      height: 164px;
      line-height: 164px;
      text-align: center;
      position: absolute;
      line-height: 0px;
      top: 0;
      left: 0;
      z-index: 2;
      line-height: 164px;
    }
    .fileUp {
      vertical-align: top;
    }
    .avatar {
      width: 254px;
      height: 164px;
      line-height: 164px;
      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>
