<template>
  <el-dialog
    :title="title"
    :center="true"
    align="left"
    top="10vh"
    width="940px"
    @close="showModelThis = false"
    :close-on-click-modal="false"
    :visible.sync="showModelThis"
    v-loading="loading"
    element-loading-text="拼命加载中"
    element-loading-spinner="el-icon-loading"
    element-loading-background="rgba(0, 0, 0, 0.8)"
  >
    <el-card style="margin-top: -20px">
      <el-row :gutter="10">
        <el-col :span="24">
          <el-form
            ref="ruleForm"
            :model="ruleForm"
            status-icon
            :size="'mini'"
            :rules="rulesThis"
            label-width="85px"
            class="demo-ruleForm"
          >
            <el-row>
              <el-col :span="12">
                <el-form-item label="异常数量" prop="num">
                  <digital-input
                    :values="ruleForm.num"
                    :placeholder="'异常数量'"
                    :min="0"
                    :disabled="false"
                    :max="1000000000"
                    :position="'right'"
                    :precision="0"
                    :size="'mini'"
                    :controls="false"
                    :append="''"
                    @reschange="number_change($event, 'num')"
                  />
                </el-form-item>
                <el-form-item label="异常原因" prop="error_code">
                  <el-select
                    v-model="ruleForm.error_code"
                    placeholder="异常原因"
                    style="width: 100%"
                    @change="elSelectChange"
                  >
                    <el-option
                      v-for="item in options"
                      :key="item.result_code"
                      :label="item.result"
                      :value="item.result_code"
                      :disabled="item.status === '0'"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="异常备注" prop="remark">
                  <el-input
                    type="textarea"
                    maxlength="250"
                    show-word-limit
                    placeholder="异常备注"
                    :autosize="{ minRows: 3, maxRows: 3 }"
                    v-model="ruleForm.remark"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="异常图片" prop="error_img">
                  <div class="el-form-item-error-img">
                    <ul>
                      <li
                        v-for="(item, index) in ruleForm.error_img"
                        :key="item"
                      >
                        <img :src="item" alt="" />
                        <i class="el-icon-close" @click="imgClose(index)"></i>
                      </li>
                    </ul>
                    <div
                      class="btnupload"
                      v-if="ruleForm.error_img.length < 5"
                      style="position: relative"
                      @click="open"
                    >
                      <i class="el-icon-plus avatar-uploader-icon"></i>
                      <file-upload
                        class="Upload"
                        :accept="'.jpg,.png,.jpeg'"
                        :multiple="true"
                        :uploadcondition="beforeAvatarUpload"
                        @UploadErrorEvent="UploadErrorEvent"
                        @UploadSuccessEvent="UploadSuccessEvent"
                      />
                    </div>
                  </div>
                </el-form-item>
              </el-col>
              <el-col :span="21">
                <div class="txt-tips fl">
                  <p>
                    <span sty>大小：小于1MB；</span
                    ><span>类型：jpg.png.jpeg</span>
                  </p>
                </div>
              </el-col>
              <el-col :span="3" style="text-align: right">
                <el-button
                  class="fr"
                  type="primary"
                  :size="'mini'"
                  @click="submitForm"
                  >保 存
                </el-button>
              </el-col>
            </el-row>
          </el-form>
        </el-col>
      </el-row>
    </el-card>
  </el-dialog>
</template>
   <script>
import asyncRequest from "@/apis/service/purchaseIn/purchaseOrder";
import resToken from "@/mixins/resToken";

export default {
  name: "purchaseOrder",
  props: ["showModel", "id", "sitem", "allnum"],
  mixins: [resToken],
  data() {
    const validate_num_0 = (rule, value, callback) => {
      const { required } = rule;
      if (required && value === "") {
        callback(new Error("不能为空！"));
      } else if (
        required &&
        (value === "0" ||
          value === "0." ||
          value === "0.0" ||
          value === "0.00" ||
          value === "0.000")
      ) {
        callback(new Error("不能为零！"));
      } else {
        callback();
      }
    };
    return {
      showModelThis: this.showModel,
      loading: false,
      title: "",
      newTime: "",
      options: [],
      ruleForm: {
        num: "",
        error_code: "",
        error_msg: "",
        error_img: [],
        remark: "",
      },
      show: false,
      rulesThis: this.rules,
      rules: {
        num: [
          {
            required: true,
            validator: validate_num_0,
            trigger: "blur",
          },
        ],
        error_code: [
          {
            required: true,
            message: "请选择异常原因",
            trigger: "change",
          },
        ],
        error_img: [
          {
            type: "array",
            required: true,
            message: "异常图片不能为空！",
            trigger: "change",
          },
        ],
        remark: [
          {
            required: true,
            message: "异常备注不能为空！",
            trigger: "blur",
          },
        ],
      },
    };
  },
  watch: {
    showModel: function (val) {
      this.showModelThis = val;
      if (val) {
        this.initForm();
      }
    },
    showModelThis(val) {
      if (!val) {
        this.$emit("cancel");
      }
    },
  },
  methods: {
    async initForm() {
      this.loading = true;
      this.rulesThis = this.rules;
      if (this.id === -1) {
        this.title = "新建异常记录";
      } else {
        this.title = "编辑异常记录";
      }
      await this.getresultlist();
      await this.resetForm();
      this.loading = false;
    },
    number_change(e, key) {
      this.ruleForm[key] = e + "" || "0";
      this.$refs.ruleForm.validateField(key);
    },
    //异常原因筛选
    elSelectChange(e) {
      let oindex = this.options.findIndex((v) => v.result_code === e);
      this.ruleForm.error_msg =
        oindex !== -1 ? this.options[oindex].result : "";
    },
    imgClose(index) {
      this.ruleForm.error_img.splice(index, 1);
      this.$refs.ruleForm.validateField("error_img");
    },
    async getresultlist() {
      const res = await asyncRequest.resultlist({
        page: 1,
        size: 100,
        type: "1",
        status: "",
      });
      if (res && res.code === 0 && res.data) {
        const { list } = res.data;
        this.options = list;
      } else if (res && res.code >= 100 && res.code <= 104) {
        await this.logout();
      } else {
        this.$message.warning(res.message);
      }
    },
    async resetForm() {
      // 重置
      await this.$nextTick(() => {
        if (this.$refs.ruleForm) {
          this.$refs.ruleForm.resetFields();
          this.$refs.ruleForm.clearValidate();
          const { num, error_code, error_msg, error_img, remark, index } =
            this.sitem;
          this.ruleForm = {
            num: num || "0",
            index: this.id,
            error_code: error_code || "",
            error_msg: error_msg || "",
            error_img: error_img || [],
            remark: remark || "",
          };
        }
      });
    },
    async submitForm() {
      await this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          const item = JSON.parse(JSON.stringify(this.ruleForm));
          if (item.num + "" === "0") {
            this.$message.warning("异常数量不能为0！");
            return;
          }
          this.showModelThis = false;


          console.log("111111111111111111",item)
          this.$emit("refresh", item);
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    getNewTime() {
      this.newTime = new Date().valueOf();
    },
    open() {
      this.show = true;
    },
    //图片上传失败
    UploadErrorEvent(res) {
      if (res !== "break") {
        this.$message.error("图片上传失败!");
        this.$refs.ruleForm.validateField("error_img");
      }
    },
    //图片上传成功
    async UploadSuccessEvent(data) {
      const { url } = data;
      if (url === "noToken") {
        await this.logout();
      } else {
        this.ruleForm.error_img.push(url);
        this.$message.success("图片上传成功!");
        this.$refs.ruleForm.validateField("error_img");
      }
    },
    //判断图片规格
    beforeAvatarUpload(file) {
      let isJPG = false,
        isLt2M = false;
      if (file) {
        if (
          file.type === "image/jpg" ||
          file.type === "image/png" ||
          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>
.stockInDetail {
  .el-form-item-error-img {
    width: 100%;
    ul {
      width: 100%;
      li {
        float: left;
        border: 1px solid rgb(220, 223, 230);
        // border-left: 0;
        box-sizing: border-box;
        width: 50px;
        height: 50px;
        line-height: 50px;
        position: relative;
        img {
          display: inline-block;
          width: 100%;
          height: 100%;
        }
        .el-icon-close {
          position: absolute;
          top: 0;
          right: 0;
          z-index: 2;
          width: 20px;
          height: 20px;
          text-align: center;
          line-height: 20px;
          font-size: 14px;
          &:hover {
            color: #6954f0;
          }
        }
      }
    }
  }
}
</style>
   