<template>
  <el-form
    v-loading="loading"
    :model="ruleForm"
    :rules="rules"
    :size="'mini'"
    status-icon
    ref="ruleForm"
    label-width="95px"
    class="demo-ruleForm"
  >
    <el-row>
      <el-col :span="8">
        <el-form-item label="发货总数" prop="send_num" required>
          <el-input
            disabled
            placeholder="发货总数"
            v-model="ruleForm.send_num"
            maxlength="100"
          />
        </el-form-item>
        <el-form-item label="物流费用" prop="post_fee">
          <digital-input
            :values="ruleForm.post_fee"
            :placeholder="'物流费用'"
            :min="0"
            :disabled="type === 'view' || type === 'post_fee'"
            :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="16">
        <el-form-item label="备注" prop="remark">
          <el-input
            type="textarea"
            placeholder="备注"
            :autosize="{ minRows: 4, maxRows: 4 }"
            v-model="ruleForm.remark"
            maxlength="100"
          />
        </el-form-item>
      </el-col>
      <el-col :span="24">
        <el-row>
          <el-col :span="8">
            <el-form-item label="物流公司" prop="post_name">
              <search-express
                :value="ruleForm.post_name"
                :placeholder="'物流公司'"
                :names="''"
                :size="'mini'"
                :is-detail="false"
                @searchChange="handleCompany"
              /> </el-form-item
          ></el-col>
          <el-col
            :span="8"
            v-for="(domain, index) in ruleForm.post_code"
            :key="domain.key"
          >
            <el-form-item
              :label="'物流单号' + (index + 1)"
              :key="domain.key"
              :prop="'post_code.' + index + '.value'"
              :rules="const_post"
            >
              <el-input placeholder="物流单号" v-model="domain.value" maxlength="20">
                <el-button
                  slot="append"
                  icon="el-icon-delete"
                  @click.prevent="removeDomain(index)"
                ></el-button>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-col>

      <el-col :span="24" style="text-align: right; padding: 0 0 16px 0">
        <el-button
          type="warning"
          :size="'mini'"
          @click="addDomain"
          icon="el-icon-circle-plus-outline"
          >添加快递单号</el-button
        >
        <el-button type="primary" :size="'mini'" @click="submitForm" icon="el-icon-search"
          >保 存
        </el-button>
      </el-col>
    </el-row>
  </el-form>
</template>
<script>
import asyncRequest from "@/apis/service/sellOut/sellOutOrder";
import resToken from "@/mixins/resToken";
import { isnumber, isAlphanumeric } from "@/utils/validate";
// import ladderPriceVue from "@/views/goodStore/goodsCost/ladderPrice.vue";
export default {
  name: "wsmInOrderAdd",
  props: ["id", "sitem", "newTime"],
  mixins: [resToken],
  data() {
    const validate_num = (rule, value, callback) => {
      const { required } = rule;
      if (required && value === "") {
        callback(new Error("不能为空！"));
      } else {
        callback();
      }
    };
    const validateCode = (rule, value, callback) => {
      const { required } = rule;
      const l = value.length;
      if (required) {
        if (value === "") {
          callback(new Error("物流单号不能为空!"));
        } else if (value === "0") {
          callback();
        } else if (l < 10 || l > 20) {
          callback(new Error("仅支持0;纯数字或字母数字组合(10~20位)!"));
        } else if (isnumber(value)) {
          callback();
        } else if (!isAlphanumeric(value)) {
          console.log(!isAlphanumeric(value));
          callback(new Error("仅支持0;纯数字或字母数字组合(10~20位)!"));
        } else {
          callback();
        }
      } else {
        callback();
      }
    };

    return {
      loading: true,
      const_post: {
        required: true,
        validator: validateCode,
        trigger: "blur",
      },
      ruleForm: {
        outCode: "",
        send_num: "",
        post_name: [],
        post_code: [
          {
            value: "",
            key: Date.now(),
          },
        ],
        post_fee: "",
        remark: "",
        // sendtime: "",
      },
      rules: {
        post_name: {
          type: "array",
          required: true,
          trigger: "change",
          message: "请输入物流公司",
        },
        post_code: {
          required: true,
          validator: validateCode,
          trigger: "blur",
        },
        post_fee: {
          required: true,
          validator: validate_num,
          trigger: "blur",
        },
        remark: {
          required: true,
          validator: validate_num,
          trigger: "blur",
        },
      },
    };
  },
  watch: {
    newTime: function (val) {
      if (val) {
        this.initForm();
      }
    },
  },
  mounted() {
    this.initForm();
  },
  methods: {
    async initForm() {
      this.loading = true;
      await this.resetForm();
      this.loading = false;
    },
    removeDomain(index) {
      if (this.ruleForm.post_code.length === 1) {
        this.$message.warning("至少填写一个快递单号！");
        return;
      }
      if (index !== -1) {
        this.ruleForm.post_code.splice(index, 1);
      }
    },
    addDomain() {
      this.ruleForm.post_code.push({
        value: "",
        key: Date.now(),
      });
    },
    //初始化表单
    async resetForm() {
      await this.$nextTick(() => {
        if (this.$refs.ruleForm) {
          this.$refs.ruleForm.resetFields();
          this.$refs.ruleForm.clearValidate();

          const {
            outCode,
            send_num,
            post_code,
            post_name,
            post_fee,
            remark,
          } = this.sitem;
          this.ruleForm = {
            outCode: outCode || "",
            send_num: send_num || "",
            post_name: post_name ? [post_name] : [],
            post_code: [
              {
                value: post_code || "",
                key: Date.now(),
              },
            ],
            post_fee: post_fee || "",
            remark: remark || "",
            // sendtime: "",
          };
        }
      });
    },
    // 保存更改
    async submitForm() {
      await this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          if (this.loading) {
            return;
          }
          this.loading = true;
          const { post_name, post_code } = this.ruleForm;
          const postName = post_name.toString();
          let post_list = "",
            isok = true,
            is_has = 0;
          post_code.forEach((si, sii) => {
            post_list += `${sii === 0 ? "" : ","}${si.value}`;
            if (si.value === "0") {
              is_has++;
              if (postName !== "其他") {
                isok = false;
              }
            }
          });
          if (!isok) {
            this.$message.warning("快递单号填零，物流公司必须选择其他！");
            this.loading = false;
            return;
          }
          if (is_has > 0 && post_code.length > 2) {
            this.$message.warning("多物流单号不允许填零！");
            this.loading = false;
            return;
          }

          let model = JSON.parse(JSON.stringify(this.ruleForm));
          model.post_name = postName;
          model.post_code = post_list;

          delete model["send_num"];
          delete model["page"];
          console.log(model);

          const { code, message } = await asyncRequest.saleoutsend(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 {
            this.$message.warning(message);
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    handleCompany(e) {
      const { code, id, label } = e;
      this.ruleForm.post_name = label ? [label] : [];
      this.$refs.ruleForm.validateField("post_name");
    },
    number_change(e, key) {
      this.ruleForm[key] = e + "" || "0";
      this.$refs.ruleForm.validateField(key);
    },
  },
};
</script>

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