<template>
  <el-form
    ref="ruleForm"
    :loading="loading"
    :model="ruleForm"
    status-icon
    :size="'small'"
    :rules="rulesThis"
    label-width="80px"
    style="width: 100%"
    class="demo-ruleForm"
  >
    <el-row>
      <el-col :span="6">
        <el-form-item label="收货情况" prop="is_receive">
          <el-select
            style="width: 100%"
            :disabled="disabled"
            v-model="ruleForm.is_receive"
            @change="is_receive_change"
            placeholder="收货情况"
          >
            <el-option
              v-for="item in is_receive_options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="发货总量" prop="send_num" required>
          <el-input
            disabled
            v-model="ruleForm.send_num"
            maxlength="10"
            placeholder="发货总量"
          ></el-input>
        </el-form-item>
        <el-form-item label="异常数量" prop="num">
          <digital-input
            :values="ruleForm.num"
            :placeholder="'异常数量'"
            :min="0"
            :disabled="ruleForm.is_receive === '0'"
            :max="ruleForm.send_num"
            :position="'right'"
            :precision="0"
            :size="'small'"
            :controls="false"
            :append="''"
            @reschange="number_change($event, 'num')"
          />
        </el-form-item>
      </el-col>
      <el-col :span="9">
        <el-form-item label="异常原因" prop="errorCode">
          <el-select
            style="width: 100%"
            :disabled="ruleForm.is_receive === ''"
            v-model="ruleForm.errorCode"
            placeholder="异常原因"
          >
            <el-option
              v-for="item in reason_options"
              :key="item.id"
              :label="item.result"
              :value="item.result_code"
              :disabled="item.status == 0"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="9">
        <el-form-item label="期望意愿" prop="except_code">
          <el-select
            style="width: 100%"
            :disabled="ruleForm.is_receive === ''"
            v-model="ruleForm.except_code"
            placeholder="期望意愿"
          >
            <el-option
              v-for="item in expect_options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="18">
        <el-form-item label="异常备注" prop="remark">
          <el-input
            placeholder="异常备注"
            v-model="ruleForm.remark"
            type="textarea"
            :rows="3"
            :disabled="disabled"
            maxlength="250"
            show-word-limit
          />
        </el-form-item>
      </el-col>
      <el-col :span="20">
        <el-form-item label="异常图片" prop="img">
          <div class="el-form-item-error-img">
            <ul>
              <li
                class="images_li"
                :style="getMargin_li()"
                v-for="(item, index) in ruleForm.img"
                :key="item"
              >
                <img :src="item" alt="" style="width: 50px; height: 50px" />
                <i
                  class="el-icon-close"
                  v-if="
                    id === 'add' || (status === '0' && powers.some((i) => i == '005'))
                  "
                  @click="imgClose(index)"
                ></i>
              </li>
            </ul>
            <div
              class="btnupload"
              :style="getMargin()"
              v-if="ruleForm.img.length < 5 && isShow"
              style="position: relative"
              @click="show = true"
            >
              <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="4" style="text-align: right">
        <el-button
          type="primary"
          @click="submitForm"
          v-if="id === 'add' || (status === '0' && powers.some((i) => i == '005'))"
          >保 存</el-button
        >
      </el-col>
    </el-row>
  </el-form>
</template>
<script>
import { isnumber } from "@/utils/validate.js";
import asyncRequest from "@/apis/service/sellOut/sellAfterApply";
import resToken from "@/mixins/resToken";
export default {
  name: "handover",
  props: ["id", "sitem", "showModelThis", "newTime", "orderCode", "outCode"],
  mixins: [resToken],
  data() {
    const validatenumbers = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("异常数量不能为空！"));
      } else {
        if (!isnumber(value)) {
          callback(new Error("异常数量必须为数字"));
        } else {
          callback();
        }
      }
    };
    return {
      isShow: true,
      loading: false,
      disabled: true,
      status: "", //存储详情接口返的状态
      showModelThis: this.showModel,
      is_receive_options: [
        {
          value: "1",
          label: "已收到货",
        },
        {
          value: "0",
          label: "未收到货",
        },
      ],
      resign_name: "", //离职人
      hand_name: "", //交接人
      ruleForm: {
        is_receive: "",
        send_num: "",
        order_type: "",
        outCode: "", //
        stock_out_numbers: "", //发货申请单编号
        num: "", //异常数量
        errorCode: "", //异常原因
        except_code: "", //期望意愿
        img: [],
        remark: "", //异常备注
      },
      rulesThis: this.rules,
      // 验证规则
      rules: {
        is_receive: [
          {
            required: true,
            message: "请选择收货情况",
            trigger: "change",
          },
        ],
        num: [
          {
            required: true,
            trigger: "blur",
            validator: validatenumbers,
          },
        ],
        errorCode: [
          {
            required: true,
            message: "请选择异常原因",
            trigger: "change",
          },
        ],
        except_code: [
          {
            required: true,
            message: "请选择期望意愿",
            trigger: "change",
          },
        ],
        img: [
          {
            type: "array",
            required: true,
            message: "异常图片不能为空！",
            trigger: "change",
          },
        ],
        remark: [
          {
            required: true,
            message: "请输入异常备注",
            trigger: "blur",
          },
        ],
      },
      reason_options: [],
      expect_options: [],
      expect_options1: [
        {
          value: "1",
          label: "退货",
        },
        {
          value: "2",
          label: "换货",
        },
      ],
      expect_options0: [
        {
          value: "1",
          label: "退货",
        },
        {
          value: "2",
          label: "补发",
        },
      ],
      expect_value: "", //期望意愿
      code: "",
    };
  },
  computed: {
    powers() {
      const tran =
        this.$store.getters.btnList.find((item) => item.menu_route == "handoverDetail") ||
        {};
      const { action } = tran ?? {};
      return action ?? [];
    },
  },
  mounted() {
    this.initForm();
  },
  watch: {
    id: function (val) {
      if (val) {
        this.initForm();
      }
    },
    newTime: function (val) {
      if (val) {
        this.initForm();
      }
    },
  },
  methods: {
    closeAdd() {
      this.showModelThis = false;
    },
    async initForm() {
      this.loading = true;
      this.status = "";
      this.rulesThis = this.rules;
      this.disabled = false;
      await this.resetForm();
      this.loading = false;
    },
    async initData() {
      if (this.sitem) {
        let { returnCode } = this.sitem;
        let model = {
          returnCode,
        };
        const res = await asyncRequest.detail(model);
        if (res && res.code === 0 && res.data) {
          let {
            error_num,
            error_img,
            error_remark,
            except_code,
            error_code,
          } = console.log(res.data);
          this.ruleForm = {
            stock_out_numbers: "", //发货申请单编号
            num: error_num, //异常数量
            errorCode: error_code, //异常原因
            except_code: except_code, //期望意愿
            img: [error_img],
            remark: error_remark, //异常备注
          };
        } else if (res && res.code >= 100 && res.code <= 104) {
          await this.logout();
        } else {
          this.$message.warning(res.message);
        }
      }
    },

    async is_receive_change() {
      const { is_receive } = this.ruleForm;
      this.ruleForm.errorCode = "";
      this.ruleForm.except_code = "";
      if (is_receive === "0") {
        this.ruleForm.num = this.ruleForm.send_num;
      }
      this.expect_options = [];
      this.reason_options = [];
      if (is_receive !== "") {
        this.expect_options = JSON.parse(
          JSON.stringify(is_receive === "1" ? this.expect_options1 : this.expect_options0)
        );
        await this.getReason(is_receive === "1" ? "3" : "6"); //获取异常原因
      }
    },
    async number_change(e, key) {
      this.ruleForm[key] = e + "" || "0";
      this.$refs.ruleForm.validateField(key);
    },
    async resetForm() {
      this.resign_name = "";
      this.hand_name = "";
      this.status = "";
      // 重置
      await this.$nextTick(() => {
        if (this.$refs.ruleForm) {
          this.$refs.ruleForm.resetFields();
          this.$refs.ruleForm.clearValidate();
          let { send_num } = this.sitem;
          this.ruleForm = {
            is_receive: "",
            send_num: send_num || "",
            num: send_num || "", //异常数量
            errorCode: "", //异常原因
            except_code: "", //期望意愿
            img: [],
            outCode: this.code,
          };
        }
      });
    },
    async submitForm() {
      await this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          if (this.loading) {
            return;
          }
          this.loading = true;
          let model = JSON.parse(JSON.stringify(this.ruleForm));
          model.outCode = this.sitem.outCode;
          model.img = model.img.toString();
          const { code, data, message } = await asyncRequest.add(model);
          this.loading = false;
          if (code === 0) {
            const title = this.id === "add" ? "添加成功！" : "修改成功！";
            this.$notify.success({
              title,
              message: "",
            });
            this.$emit("refresh", false);
          } else if (code >= 100 && code <= 104) {
            await this.logout();
          } else {
            this.$message.warning(message);
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },

    // 获取异常原因
    async getReason(type) {
      let model = {
        type: type,
        page: 1,
        size: 100,
      };
      const res = await asyncRequest.reasonList(model);
      this.loading = false;
      if (res && res.code === 0) {
        this.reason_options = res.data.list;
      } else if (res && res.code >= 100 && res.code <= 104) {
        await this.logout();
      } else {
        this.$message.warning(res.message);
      }
    },
    //图片上传失败
    UploadErrorEvent(res) {
      if (res !== "break") {
        this.$message.error("图片上传失败!");
        this.$refs.ruleForm.validateField("img");
      }
    },

    //图片上传成功
    async UploadSuccessEvent(data) {
      const { url } = data;
      if (url === "noToken") {
        await this.logout();
      } else {
        this.ruleForm.img.push(url);
        this.$message.success("图片上传成功!");
        this.$refs.ruleForm.validateField("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;
    },
    imgClose(index) {
      this.ruleForm.img.splice(index, 1);
      this.$refs.ruleForm.validateField("img");
    },
    getMargin() {
      if (this.ruleForm.img.length == 0) {
        return "margin:0;";
      } else if (this.ruleForm.img.length < 3) {
        return "margin:0px 0 0 10px";
      } else {
        return "margin:10px 0 0 10px";
      }
    },
    getMargin_li() {
      if (this.ruleForm.img.length <= 3) {
        return "margin:0 0 0 10px";
      } else {
        return "margin:10px 0 0 10px";
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.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: 16px;
        height: 16px;
        text-align: center;
        line-height: 16px;
        font-size: 13px;
        &:hover {
          color: #6954f0;
        }
      }
    }
  }
}
.images_li {
  // width: 50px;
  // height: 50px;
  float: left;
}
.btnupload {
  float: left;
  border: 1px solid rgb(220, 223, 230);
  // border-left: 0;
  box-sizing: border-box;
  width: 50px;
  height: 50px;
  line-height: 50px;
  text-align: center;
}
.Upload {
  width: 50px;
  height: 50px;
  line-height: 50px;
  text-align: center;
  position: absolute;
  line-height: 0px;
  top: 0;
  left: 0;
  z-index: 2;
  line-height: 50px;
}
.avatar-uploader-icon {
  font-size: 33px;
  color: #8c939d;
  width: 50px;
  height: 50px;
  line-height: 50px;
  text-align: center;
}
</style>
