<template>
  <el-form
    ref="ruleForm"
    v-loading="loading"
    :model="ruleForm"
    :rules="rules"
    :size="'mini'"
    status-icon
    label-width="95px"
    class="demo-ruleForm"
  >
    <el-row>
      <el-col :span="18">
        <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-form-item label="物流公司" prop="post_name">
          <search-express
            :value="ruleForm.post_name"
            :placeholder="'物流公司'"
            :names="''"
            :size="'mini'"
            :order_source="order_source"
            :is-detail="false"
            @searchChange="handleCompany"
          /> </el-form-item>
        <el-col
          v-for="(domain, index) in ruleForm.post_code"
          :key="domain.key"
          :span="12"
        >
          <el-form-item
            :key="domain.key"
            :label="'物流单号' + (index + 1)"
            :prop="'post_code.' + index + '.value'"
            :rules="const_post"
          >
            <el-input
              v-model="domain.value"
              placeholder="物流单号"
              minlength="9"
              maxlength="20"
            >
              <el-button
                slot="append"
                icon="el-icon-delete"
                @click.prevent="removeDomain(index)"
              />
            </el-input>
          </el-form-item>
        </el-col>

        <el-col :span="24" style="text-align: right; padding: 0 0 16px 0">
          <el-button
            type="warning"
            :size="'mini'"
            icon="el-icon-circle-plus-outline"
            @click="addDomain"
          >添加快递单号</el-button>
          <el-button
            type="primary"
            :size="'mini'"
            icon="el-icon-search"
            @click="submitForm"
          >保 存
          </el-button>
        </el-col>
      </el-col>
    </el-row>
  </el-form>
</template>
<script>
import asyncRequest from '@/apis/service/sellOut/deliveryWorkOrder'
import resToken from '@/mixins/resToken'
import { isnumber, isNumeric } from '@/utils/validate'
export default {
  name: 'WsmInOrderAdd',
  mixins: [resToken],
  props: ['id', 'sitem', 'newTime'],
  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 (l < 9 || l > 20) {
          callback(new Error('仅支持纯数字或字母数字组合(9~20位)!'))
        } else if (isnumber(value)) {
          callback()
        } else if (!isNumeric(value)) {
          console.log(!isNumeric(value))
          callback(new Error('仅支持纯数字或字母数字组合(9~20位)!'))
        } else {
          callback()
        }
      } else {
        callback()
      }
    }

    return {
      loading: true,
      order_source: '',
      const_post: {
        required: true,
        validator: validateCode,
        trigger: 'blur'
      },
      ruleForm: {
        post_name: [],
        post_code: [
          {
            value: '',
            key: Date.now()
          }
        ],
        post_fee: ''
      },
      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'
        }
      }
    }
  },
  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() {
      if (this.ruleForm.post_code.length >= 10) {
        this.$message.warning('最多只能添加10条物流单号!')
        return
      }

      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 {
            post_code,
            post_name,
            post_fee,
            remark,
            order_source
          } = this.sitem
          this.order_source = order_source
          this.ruleForm = {
            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_code, post_name, post_fee } = this.ruleForm
          const { outChildCode } = this.sitem

          const model = {
            list: [{
              post_fee,
              outChildCode,
              post_name: Array.isArray(post_name) ? post_name[0] : post_name,
              post_code: post_code.map(({ value }) => value).join(',')
            }]
          }

          const { code, message } = await asyncRequest.express(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>
