<template>
  <el-dialog
    :title="'新建入库单'"
    :center="true"
    align="left"
    top="15vh"
    width="700px"
    @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
            v-loading="loading"
            :model="ruleForm"
            :rules="rulesThis"
            status-icon
            :size="'mini'"
            ref="ruleForm"
            label-width="85px"
            class="demo-ruleForm"
          >
            <el-row>
              <el-col :span="12">
                <el-form-item
                  label="可入库总数"
                  prop="wsend_num"
                  required
                  label-width="95px"
                >
                  <el-input
                    disabled
                    :size="'mini'"
                    placeholder="可入库总数"
                    v-model="ruleForm.wsend_num"
                    maxlength="100"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="入库数量" prop="send_num">
                  <digital-input
                    :values="ruleForm.send_num"
                    :placeholder="'入库数量'"
                    :min="0"
                    :name="'ruleForm.send_num'"
                    :disabled="false"
                    :max="ruleForm.wsend_num"
                    :position="'right'"
                    :precision="0"
                    :size="'mini'"
                    :controls="false"
                    :append="''"
                    @reschange="number_change($event, 'send_num')"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="发货方式" prop="sendtype">
                  <el-select
                    v-model="ruleForm.sendtype"
                    style="width: 100%"
                    :size="'mini'"
                    :disabled="sitem && sitem.order_type === '3'"
                    placeholder="发货方式"
                    @change="sendtypeChange"
                  >
                    <el-option
                      v-for="item in options"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="物流费用" prop="post_fee">
                  <digital-input
                    :values="ruleForm.post_fee"
                    :placeholder="'物流费用'"
                    :min="0"
                    :disabled="false"
                    :max="100000000000"
                    :position="'right'"
                    :precision="2"
                    :size="'mini'"
                    :controls="false"
                    :append="'元'"
                    @reschange="number_change($event, 'post_fee')"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="24" v-if="ruleForm.sendtype === '1'">
                <el-form-item label="物流公司" prop="post_company">
                  <search-express
                    :value="ruleForm.post_company"
                    :placeholder="'物流公司'"
                    :names="''"
                    :order_source="order_source"
                    :size="'mini'"
                    :is-detail="false"
                    @searchChange="handleCompany"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="24" v-if="ruleForm.sendtype === '1'">
                <el-form-item label="物流单号" prop="post_code">
                  <el-input
                    placeholder="物流单号"
                    :size="'mini'"
                    v-model="ruleForm.post_code"
                    maxlength="100"
                  />
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="发货时间" prop="post_time">
                  <el-date-picker
                    v-model="ruleForm.post_time"
                    type="datetime"
                    style="width: 100%"
                    :size="'mini'"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    placeholder="发货时间"
                    :picker-options="pickerOptions"
                    @change="selectTime"
                  >
                  </el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="12" style="text-align: right">
                <el-button 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 resToken from "@/mixins/resToken";
import asyncRequest from "@/apis/service/purchaseIn/purchaseOrder";
import { isAlphanumeric } from "@/utils/validate";
export default {
  name: "wsmInOrderAdd",
  props: ["showModel", "id", "sitem"],
  mixins: [resToken],
  data() {
    const validate_num = (rule, value, callback) => {
      const { required } = rule;
      if (required && value === "") {
        callback(new Error("不能为空！"));
      } else {
        callback();
      }
    };
    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();
      }
    };
    const validateCode = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("不能为空!"));
      } else {
        if (!isAlphanumeric(value)) {
          callback(new Error("仅支持字母和数字!"));
        } else {
          callback();
        }
      }
    };

    return {
      showModelThis: this.showModel,
      loading: true,
      order_source: "",
      ruleForm: {
        wsm_mobile: "",
        wsm_contactor: "",
        wsm_addr: "",
        cgdNo: "",
        wsm_code: "",
        post_company: [],
        post_code: "",
        post_fee: "",
        post_time: "",
        send_num: "",
        sendtype: "1",
        status: "1",
      },
      rulesThis: this.rules,
      options: [
        {
          value: "1",
          label: "公司自提",
        },
        {
          value: "2",
          label: "供应商包邮",
        },
      ],
      pickerOptions: {
        disabledDate: (time) => {
          return time.getTime() > new Date().valueOf();
        },
      },
      rules: {
        send_num: [
          {
            required: true,
            validator: validate_num_0,
            trigger: "blur",
          },
        ],
        post_company: [
          {
            type: "array",
            required: true,
            trigger: "change",
            message: "请输入物流公司",
          },
        ],
        sendtype: [
          {
            required: true,
            trigger: "change",
            message: "选择发货方式",
          },
        ],
        post_code: [
          {
            required: true,
            validator: validateCode,
            trigger: "blur",
          },
        ],
        post_fee: [
          {
            required: true,
            validator: validate_num,
            trigger: "blur",
          },
        ],
        post_time: [
          {
            required: true,
            message: "请选择发货时间",
            trigger: "change",
          },
        ],
      },
    };
  },
  watch: {
    showModel: function (val) {
      this.showModelThis = val;
      if (val) {
        this.initForm();
      }
    },
    showModelThis(val) {
      if (!val) {
        this.$emit("cancel");
      }
    },
  },
  methods: {
    async initForm() {
      this.loading = true;
      console.log(this.sitem);
      this.rulesThis = this.rules;
      await this.resetForm();
      this.loading = false;
    },
    //初始化表单
    async resetForm() {
      await this.$nextTick(() => {
        if (this.$refs.ruleForm) {
          this.$refs.ruleForm.resetFields();
          this.$refs.ruleForm.clearValidate();
          const { cgdNo, wsend_num, goodinfo, order_source } = this.sitem;
          const { send_way } = goodinfo;
          this.order_source = order_source || "";
          this.ruleForm = {
            wsm_mobile: "",
            wsm_contactor: "",
            wsm_addr: "",
            cgdNo: cgdNo || "",
            wsm_code: "",
            post_company: [],
            post_code: "",
            post_fee: "",
            post_time: "",
            wsend_num: wsend_num || "0",
            sendtype: send_way === "0" ? "1" : "2" || "1",
            send_num: wsend_num || "0",
            status: "1",
          };
        }
      });
    },
    number_change(e, key) {
      this.ruleForm[key] = e + "" || "0";
      this.$refs.ruleForm.validateField(key);
    },
    sendtypeChange() {
      const { sendtype } = this.ruleForm;
      this.rulesThis.post_code[0].required = sendtype === "1";
      this.rulesThis.post_company[0].required = sendtype === "1";
    },
    // 保存更改
    async submitForm() {
      console.log(this.rules);
      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.post_company = model.post_company.toString();
          let time1 = new Date(model.post_time).valueOf();
          let time2 = new Date().valueOf();
          if (time1 >= time2) {
            this.$message.warning(`发货时间不能选择未来时间！`);
            this.loading = false;
            return;
          }
          const { code, message } = await asyncRequest.orderinadd(model);
          this.loading = false;
          if (code === 0) {
            this.$notify.success({
              title: "添加成功",
              message: "",
            });
            this.$emit("refresh"); //抛出事件给详情页。
          } else if (code >= 100 && code <= 104) {
            await this.logout();
          } else if (code === "1009") {
            this.$message.warning(`${message},请刷新采购单详情重试！`);
          } else {
            this.$message.warning(message);
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    handleCompany(e) {
      console.log(e);
      this.ruleForm.post_company = e && e.code ? [e.label] : [];
      this.$refs.ruleForm.validateField("post_company");
    },
  },
};
</script>

<style lang="scss" scoped>
.purchaseOrder {
}
</style>
