<template>
  <el-dialog
    v-loading="loading"
    :title="'新建退货单'"
    :center="true"
    align="left"
    top="8vh"
    width="950px"
    :close-on-click-modal="false"
    :visible.sync="showModelThis"
    element-loading-text="拼命加载中"
    element-loading-spinner="el-icon-loading"
    element-loading-background="rgba(0, 0, 0, 0.8)"
    @close="showModelThis = false"
  >
    <el-card style="margin: -20px 0 0 0">
      <el-form
        ref="ruleForm"
        :model="ruleForm"
        status-icon
        :rules="rulesThis"
        :size="'mini'"
        label-width="80px"
        class="demo-ruleForm"
      >
        <el-row>
          <el-col :span="24">
            <el-form-item label="退货原因" prop="errorCode">
              <abnormal-cause
                :value="ruleForm.errorCode"
                :placeholder="'退货原因'"
                :type="'5'"
                :size="'mini'"
                @searchChange="errorCode_change"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="退货备注" prop="remark">
              <el-input
                v-model="ruleForm.remark"
                :disabled="isDetail"
                type="textarea"
                :rows="2"
                maxlength="250"
                show-word-limit
                placeholder="请填写备注"
              /> </el-form-item></el-col>
          <el-col :span="24">
            <el-row>
              <el-col :span="8">
                <el-form-item label="可退数量" prop="good_num">
                  <el-input
                    v-model="ruleForm.good_num"
                    :disabled="true"
                    placeholder="可退数量"
                    maxlength="10"
                  />
                </el-form-item>
              </el-col>

              <el-col :span="8">
                <el-form-item label="退货数量" prop="thnum">
                  <digital-input
                    :values="ruleForm.thnum"
                    :placeholder="'退货数量'"
                    :min="0"
                    :disabled="true"
                    :max="ruleForm.returnT"
                    :position="'right'"
                    :precision="0"
                    :size="'mini'"
                    :controls="false"
                    :append="''"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8" style="text-align: right">
                <el-button
                  type="primary"
                  :size="'mini'"
                  @click="submitForm"
                >保 存
                </el-button>
                <el-button
                  v-if="!isDetail"
                  :size="'mini'"
                  @click="showModelThis = false"
                >关 闭</el-button>
              </el-col>
            </el-row>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
  </el-dialog>
</template>
<script>
import asyncRequest from '@/apis/service/sellOut/salesOrder/detail'
import resToken from '@/mixins/resToken'
import { isnumber } from '@/utils/validate'
export default {
  name: 'SellReturn',
  mixins: [resToken],
  props: ['showModel', 'id', 'isDetail', 'sitem'],
  data() {
    return {
      loading: false,
      showModelThis: this.showModel,
      statusOptions: [
        { id: '0', label: '待公司采购' },
        { id: '1', label: '待库管发货' },
        { id: '2', label: '已发货待收货' },
        { id: '3', label: '已收货' },
        { id: '4', label: '已全部退货' }
      ],
      ruleForm: {
        good_num: '',
        thnum: '',
        return_type: '1',
        orderCode: '', // 发货申请单编号
        remark: '', // 退货备注
        errorCode: '', // 退货原因
        returnT: ''
      },
      rulesThis: this.rules,
      options: [
        {
          value: '1',
          label: '无地址'
        },
        {
          value: '2',
          label: '有地址'
        }
      ],
      rules: {
        errorCode: [
          {
            required: true,
            message: '请选择退货原因',
            trigger: 'change'
          }
        ],

        thnum: [
          {
            required: true,
            message: '请输入退货数量',
            trigger: 'blur'
          }
        ],
        remark: [
          {
            required: true,
            message: '请输入退货备注',
            trigger: 'blur'
          }
        ]
      },
      get_product_go: [],
      noAddrT: 0,
      hasAddrT: 0,
      type_change: true
    }
  },
  watch: {
    showModel: function(val) {
      this.showModelThis = val
      if (val) {
        this.initForm()
      }
    },
    showModelThis(val) {
      if (!val) {
        this.$emit('cancel')
      }
    }
  },

  methods: {
    errorCode_change(e) {
      this.ruleForm.errorCode = e && e.code ? e.code : ''
      this.$refs.ruleForm.validateField('errorCode')
    },
    async initForm() {
      this.loading = true
      this.rulesThis = this.rules
      await this.resetForm()
      this.loading = false
    },

    return_type_change() {
      const { return_type } = this.ruleForm
      this.ruleForm.returnT = return_type === '1' ? this.noAddrT : this.hasAddrT
    },
    async resetForm() {
      // 重置
      await this.$nextTick(() => {
        if (this.$refs.ruleForm) {
          this.$refs.ruleForm.resetFields()
          this.$refs.ruleForm.clearValidate()
          const {
            orderCode,
            remark, // 退货备注
            errorCode, // 退货原因
            thnum,
            returnT
          } = this.sitem
          this.ruleForm = {
            thnum: thnum || '0',
            orderCode, // 发货申请单编号
            remark, // 退货备注
            errorCode, // 退货原因
            returnT: returnT || '0'
          }
        }
      })
    },

    async submitForm() {
      await this.$refs.ruleForm.validate(async(valid) => {
        if (valid) {
          if (this.loading) return

          this.loading = true
          const model = JSON.parse(JSON.stringify(this.ruleForm))
          delete model['thnum']
          delete model['returnT']

          const { code, data, message } = await asyncRequest.returnAll(model)
          this.loading = false
          if (code === 0) {
            this.$notify.success({
              title: '退货申请创建成功！',
              message: ''
            })
            this.showModelThis = false
            // 刷新
            this.$emit('refresh', false)
          } else if (code >= 100 && code <= 104) {
            await this.logout()
          } else {
            this.$message.warning(message)
          }
        } else {
          return false
        }
      })
    },
    // 保存某一行
    checkRow(rowIndex) {
      const { wsend_num, return_num } = this.get_product_go[rowIndex]
      if (!isnumber(return_num)) {
        this.$message.warning('退货数量不规范！')
        return
      }
      if (parseInt(wsend_num) < parseInt(return_num)) {
        this.$message.warning('退货数量不能大于未发货总数量！')
        return
      }
      this.get_product_go[rowIndex].edit = false
      this.get_product_go[rowIndex].newTime = new Date().valueOf() + ''
      this.$set(this.get_product_go, rowIndex, this.get_product_go[rowIndex])
    },
    // 编辑某一行
    editRow(rowIndex) {
      const list = JSON.parse(JSON.stringify(this.get_product_go))
      console.log(list)
      const index = list.findIndex((v) => v.edit === true)
      if (index !== -1) {
        this.$message.warning('请完成其他行的编辑！')
        return
      }
      this.get_product_go[rowIndex].edit = true
      this.get_product_go[rowIndex].newTime = new Date().valueOf() + ''
      this.$set(this.get_product_go, rowIndex, this.get_product_go[rowIndex])
    }
  }
}
</script>

<style lang="scss" scoped></style>
