<template>
  <div class="stockApply-com">
    <el-form
      :model="ruleForm"
      :rules="rulesThis"
      status-icon
      :size="'mini'"
      ref="ruleForm"
      label-width="90px"
      class="demo-ruleForm"
    >
      <el-row>
        <el-col :span="12">
          <el-form-item label="商品名称" prop="good_name">
            <el-input
              :disabled="
                !(
                  id === 'add' ||
                  (status === '0' && powers.some((i) => i == '005'))
                )
              "
              v-model="ruleForm.good_name"
              readonly="true"
              maxlength="100"
              :placeholder="'商品名称'"
              @focus="showGoodsModel = true"
            ></el-input>
          </el-form-item>
        </el-col>
        <!-- 采购数量 -->
        <el-col :span="5">
          <el-form-item label="采购数量" prop="goods_num">
            <digital-input
              :values="ruleForm.goods_num"
              :name="'ruleForm.goods_num'"
              :placeholder="'采购数量'"
              :min="0"
              :disabled="
                !(
                  id === 'add' ||
                  (status === '0' && powers.some((i) => i == '005'))
                )
              "
              :max="100000000000"
              :position="'right'"
              :precision="0"
              :size="'mini'"
              :controls="false"
              :append="''"
              @reschange="number_change($event, 'goods_num')"
            />
          </el-form-item>
        </el-col>
        <!-- 最晚入库时间 -->
        <el-col :span="7">
          <el-form-item
            label="最晚入库时间"
            prop="lasttime"
            label-width="120px"
          >
            <el-date-picker
              v-model="ruleForm.lasttime"
              type="date"
              style="width: 100%"
              value-format="yyyy-MM-dd"
              placeholder="最晚入库时间"
              :picker-options="pickerOptions"
              :disabled="
                !(
                  id === 'add' ||
                  (status === '0' && powers.some((i) => i == '005'))
                )
              "
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="附件" prop="file_url">
            <div
              class="file_url"
              :class="{
                disabled: !(
                  id === 'add' ||
                  (status === '0' && powers.some((i) => i == '005'))
                ),
              }"
            >
              <p v-if="ruleForm.file_url">
                <el-link
                  :underline="false"
                  :href="ruleForm.file_url"
                  target="_blank"
                  >{{ ruleForm.file_url_name }}</el-link
                >
                <el-link
                  class="fr"
                  type="info"
                  :underline="false"
                  v-if="
                    id === 'add' ||
                    (status === '0' && powers.some((i) => i == '005'))
                  "
                  ><i
                    class="el-icon-circle-close"
                    @click="close_url"
                    :size="'mini'"
                  ></i
                ></el-link>
              </p>
              <p v-else class="no">附件</p>
              <div v-if="ruleForm.file_url === ''">
                <file-upload-pdf
                  v-if="
                    id === 'add' ||
                    (status === '0' && powers.some((i) => i == '005'))
                  "
                  class="Upload"
                  :accept="'.pdf'"
                  :multiple="false"
                  :size="'mini'"
                  :uploadcondition="beforeAvatarUpload"
                  @UploadErrorEvent="UploadErrorEvent"
                  @UploadSuccessEvent="UploadSuccessEvent"
                />
              </div>
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="备注" prop="remark">
            <el-input
              type="textarea"
              :rows="2"
              placeholder="备注"
              maxlength="250"
              show-word-limit
              :disabled="
                !(
                  id === 'add' ||
                  (status === '0' && powers.some((i) => i == '005'))
                )
              "
              v-model="ruleForm.remark"
            >
            </el-input>
          </el-form-item>
        </el-col>

        <el-col :span="12" style="padding: 0 0 15px 0; text-align: right">
          <el-button
            type="primary"
            @click="submitForm"
            :size="'mini'"
            v-if="
              id === 'add' ||
              (status == '0' && powers.some((i) => i == '005'))
            "
            >保 存
          </el-button>
        </el-col>
      </el-row>
    </el-form>
    <search-good-modal
      :once="true"
      :cat_id="cat_id"
      :is_stock="'1'"
      :show-model="showGoodsModel"
      :isonline="''"
      @cancel="showGoodsModel = false"
      @resultList="addGoodsRes"
    />
  </div>
</template>
   <script>
import resToken from "@/mixins/resToken";
import asyncRequest from "@/apis/service/sellOut/stockApply";
import searchGoodModal from "@/components/search-good-modal";
export default {
  name: "stockApply",
  props: ["id", "sitem", "newTime", "type"],
  mixins: [resToken],
  components: {
    searchGoodModal,
  },
  computed: {
    powers() {
      const tran =
        this.$store.getters.btnList.find(
          (item) => item.menu_route == "stockApplyDetail"
        ) || {};
      const { action } = tran ?? {};
      return action ?? [];
    },
  },
  watch: {
    newTime: function (val) {
      if (val) {
        this.initForm();
      }
    },
  },
  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 {
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now();
        },
      },
      status: "",
      cat_id: "",
      routerId: "",
      stockCode: "",

      showGoodsModel: "",
      loading: false,
      ruleForm: {
        id: "",
        good_code: "",
        good_name: "",
        goods_num: "",
        file_url: "",
        file_url_name: "",
        lasttime: "",
        remark: "",
        // supplier_code: [],
        // supplier_name: "",
        // stock_code: [],
      },
      rulesThis: this.rules,
      rules: {
        good_name: [
          {
            required: true,
            message: "商品名称不能为空！",
            trigger: "blur",
          },
        ],
        goods_num: [
          {
            required: true,
            validator: validate_num_0,
            trigger: "blur",
          },
        ],
        lasttime: [
          {
            required: true,
            message: "请输入最晚入库时间！",
            trigger: "change",
          },
        ],
        file_url: [
          {
            required: true,
            message: "请选择附件！",
            trigger: "change",
          },
        ],
        remark: [
          {
            required: true,
            message: "备注不能为空！",
            trigger: "blur",
          },
        ],
      },
    };
  },
  mounted() {
    this.initForm();
  },
  methods: {
    async initForm() {
      this.loading = true;
      this.status = this.sitem !== undefined ? this.sitem.status : "";
      this.status = "";

      this.rulesThis = this.rules;
      await this.resetForm();
      this.loading = false;
    },

    // 执行点击商品名称的抛出事件
    addGoodsRes(e) {
      console.log(e);
      let { spuCode, good_name } = e[0];
      this.ruleForm.good_name = good_name;
      this.ruleForm.good_code = spuCode;
      this.$refs.ruleForm.validateField("good_name");
    },
    number_change(e, key) {
      this.ruleForm[key] = e + "" || "0";
      this.$refs.ruleForm.validateField(key);
    },
    closeModel() {
      this.$emit("closeModel");
    },
    close_url() {
      this.ruleForm.file_url_name = "";
      this.ruleForm.file_url = "";
      this.$refs.ruleForm.validateField("file_url");
    },
    // 重置
    async resetForm() {
      // 重置
      await this.$nextTick(() => {
        if (this.$refs.ruleForm) {
          this.$refs.ruleForm.resetFields();
          this.$refs.ruleForm.clearValidate();
          if (this.sitem) {
            const {
              id,
              good_code,
              good_name, //商品名
              good_num, //采购数量
              lasttime, //最晚入库时间
              file_url,
              file_name,
              status,
              remark,
            } = this.sitem;

            this.ruleForm = {
              id: id || "",
              good_code: good_code || "",
              good_name: good_name || "",
              goods_num: good_num || "0",
              lasttime: lasttime || "",
              file_url: file_url || "",
              file_url_name: file_name || "",
              status: status || "",
              remark: remark || "",
            };
          }
        }
      });
    },
    // 保存更改
    async submitForm() {
      await this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          if (this.loading) {
            return;
          }
          this.loading = true;
          let {
            id,
            good_code,
            good_type_code,
            goods_num,
            file_url,
            // file_name,
            // stock_code,
            lasttime,
            remark,
          } = this.ruleForm;
          let model = {
            id: id,
            good_code,
            good_type_code,
            good_num: goods_num || "",
            file_url: file_url || "",
            // file_url_name: file_name || "",
            lastime: lasttime || "",
            remark: remark || "",
          };
          let res = {};
          if (this.id === "add") {
            delete model["id"];
            res = await asyncRequest.add(model);
          } else {
            res = await asyncRequest.update(model);
          }
          if (res && res.code === 0) {
            const title = this.id === "add" ? "添加成功" : "修改成功";
            this.$notify.success({
              title,
              message: "",
            });
            this.$emit("refresh");
          } else if (res && res.code >= 100 && res.code <= 104) {
            await this.logout();
          } else {
            this.$message.warning(res.message);
          }
          this.loading = false;
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    //附件上传失败
    async UploadErrorEvent(e) {
      if (e !== "break") {
        this.$message.error("附件上传失败!");
        this.$refs.ruleForm.validateField("file_url");
      }
    },
    //附件上传成功
    async UploadSuccessEvent(data) {
      const { url, name } = data;
      if (url === "noToken") {
        await this.logout();
      } else {
        this.ruleForm.file_url_name = name;
        this.ruleForm.file_url = url;
        this.$message.success("附件上传成功!");
        this.$refs.ruleForm.validateField("file_url");
      }
    },
    //判断附件规格
    beforeAvatarUpload(file) {
      let isJPG = false,
        isLt2M = false;
      if (file) {
        if (file.type === "application/pdf") {
          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>
.stockApply-com {
  .demo-ruleForm {
    .file_url {
      position: relative;
      width: 100%;
      -webkit-appearance: none;
      background-color: #ffffff;
      background-image: none;
      border-radius: 4px;
      border: 1px solid #dcdfe6;
      -webkit-box-sizing: border-box;
      box-sizing: border-box;
      color: #606266;
      display: inline-block;
      font-size: inherit;
      height: 40px;
      line-height: 40px;
      outline: none;
      //
      -webkit-transition: border-color 0.2s cubic-bezier(0.645, 0.045, 0.355, 1);
      transition: border-color 0.2s cubic-bezier(0.645, 0.045, 0.355, 1);
      width: 100%;
      p {
        // width: calc(100% - 100px);
        width: 100%;
        padding: 0 10px;
        height: 38px;
        line-height: 38px;
        overflow: hidden;
        color: #606266;
        &.no {
          color: #c0c4cc;
        }
      }
      &.disabled {
        p {
          background-color: #f5f7fa;
          border-color: #dfe4ed;

          cursor: not-allowed;
          color: #c0c4cc;
        }
      }

      .Upload {
        z-index: 5;
        // width: ;
      }
      .yulan {
        position: absolute;
        width: 50px;
        text-align: center;
        right: 0;
        top: 0;
        cursor: pointer;
        // background: chocolate;
      }
    }
  }
}
</style>
   