<template>
  <a-modal
    centered
    class="allocateBill-basicInfo-modal"
    :footer="null"
    :maskClosable="false"
    title="新增调拨退货"
    v-model="isShow"
    @cancel="isShow = false"
    :width="800">
    <a-spin :spinning="spinning" tip="Loading...">
      <a-form-model
        id="allocateBill-basicInfo-form"
        ref="ruleForm"
        :model="form"
        :rules="rules"
        :label-col="formItemLayout.labelCol"
        :wrapper-col="formItemLayout.wrapperCol"
      >
        <a-form-model-item label="调拨退货对象" prop="targetType">
          <v-select
            code="TARGET_TYPE"
            showType="radio"
            id="allocateBill-basicInfo-targetType"
            v-model="form.targetType"
            @change="targetTypeChange"
            allowClear
            placeholder="请选择调拨退货对象"></v-select>
        </a-form-model-item>
        <a-form-model-item label="调拨退货对象名称" :prop="isDealer ? 'targetSn' : 'targetName'">
          <a-select
            v-if="isDealer"
            show-search
            id="allocateBill-basicInfo-dealerName"
            v-model="form.targetSn"
            placeholder="请输入名称搜索经销商"
            :filter-option="false"
            :not-found-content="fetching ? undefined : null"
            @search="fetchUser"
            @change="handleChange"
          >
            <a-spin v-if="fetching" slot="notFoundContent" size="small" />
            <a-select-option v-for="item in dealerData" :key="item.dealerSn" :value="item.dealerSn">{{ item.dealerName }}</a-select-option>
          </a-select>
          <department v-else-if="isDepartment" style="width: 100%;" placeholder="请选择部门" @change="departementChange" v-model="form.targetSn"></department>
          <a-input v-else v-model.trim="form.targetName" placeholder="请输入调拨退货对象名称(最多30个字符)" allowClear :maxLength="30" />
        </a-form-model-item>
        <a-form-model-item label="费用/调拨退货类型" prop="costTypeSn">
          <AllocateType id="allocateBill-basicInfo-allocateTypeSn" v-model="allocateTypeVal" placeholder="请选择费用/调拨退货类型" @change="allocateTypeChange"></AllocateType>
        </a-form-model-item>
        <a-form-model-item label="是否抓单" prop="grabFlag">
          <v-select
            code="FLAG"
            showType="radio"
            :disabled="form.targetType !== 'DEALER'"
            id="allocateBill-basicInfo-grabFlag"
            v-model="form.grabFlag"
            allowClear
            placeholder="请选择"></v-select>
        </a-form-model-item>
        <a-form-model-item label="备注" prop="remark">
          <a-textarea id="allocateBill-basicInfo-remark" :maxLength="120" v-model="form.remarks" placeholder="请输入备注(最多120个字符)" allowClear />
        </a-form-model-item>
      </a-form-model>
      <div class="btn-cont">
        <a-button type="primary" id="allocateBill-basicInfo-modal-save" @click="handleSave">保存</a-button>
        <a-button id="allocateBill-basicInfo-modal-back" @click="isShow = false" style="margin-left: 15px;">取消</a-button>
      </div>
    </a-spin>
  </a-modal>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import debounce from 'lodash/debounce'
import { VSelect } from '@/components'
import { allocateReturnSave, allocateReturnQueryBySn } from '@/api/allocateReturn'
import department from '@/views/expenseManagement/expenseReimbursement/department.js'
import { dealerSubareaScopeList } from '@/api/dealer'
import AllocateType from '@/views/common/allocateType.js'
export default {
  name: 'TransferOutBasicInfoModal',
  components: { VSelect, AllocateType, department },
  mixins: [commonMixin],
  props: {
    openModal: {
      //  弹框显示状态
      type: Boolean,
      default: false
    }
  },
  data () {
    this.fetchUser = debounce(this.fetchUser, 800)
    return {
      isShow: this.openModal, //  是否打开弹框
      spinning: false,
      formItemLayout: {
        labelCol: { span: 4 },
        wrapperCol: { span: 20 }
      },
      allocateTypeVal: [],
      form: {
        targetType: 'DEALER',
        targetSn: undefined,
        targetName: '',
        costTypeSn: undefined,
        allocateSortSn: undefined,
        allocateReturnTypeSn: undefined,
        grabFlag: '1',
        remarks: ''
      },
      rules: {
        targetType: [{ required: true, message: '请选择调往对象', trigger: 'change' }],
        targetSn: [{ required: true, message: '请选择调往对象名称', trigger: 'change' }],
        targetName: [{ required: true, message: '请输入调往对象名称', trigger: 'blur' }],
        costTypeSn: [{ required: true, message: '请选择费用/调拨退货类型', trigger: 'change' }],
        grabFlag: [{ required: true, message: '请选择是否抓单', trigger: 'change' }]
      },
      fetching: false,
      dealerData: [] //  经销商  下拉数据
    }
  },
  computed: {
    // 当前所选调往对象是否为经销商
    isDealer () {
      return this.form.targetType == 'DEALER'
    },
    isDepartment () {
      return this.form.targetType == 'DEPARTMENT'
    }
  },
  methods: {
    // 搜索经销商
    fetchUser (value) {
      console.log('fetching user', value)
      this.fetching = true
      dealerSubareaScopeList({ nameLike: value, pageNo: 1, pageSize: 20 }).then(res => {
        if (res.status == 200) {
          this.dealerData = res.data && res.data.list ? res.data.list : []
          this.fetching = false
        } else {
          this.dealerData = []
          this.fetching = false
        }
      })
    },
    // 调往对象名称  change
    handleChange (value) {
      const ind = this.dealerData.findIndex(item => item.dealerSn == value)
      this.form.targetName = this.dealerData[ind].dealerName
    },
    departementChange (v, row) {
       console.log(v,row)
       this.form.targetName = row.name
    },
    // 调拨类别 change
    allocateTypeChange (val, opt) {
      console.log(val, opt, '------------')
      this.allocateTypeVal = val
      this.form.costTypeSn = val[0] ? val[0] : ''
      this.form.allocateSortSn = val[1] ? val[1] : ''
      this.form.allocateReturnTypeSn = val[2] ? val[2] : ''
      // 名称
      this.form.costTypeName = opt[0] ? opt[0].name : ''
      this.form.allocateSortName = opt[1] ? opt[1].name : ''
      this.form.allocateReturnTypeName = opt[2] ? opt[2].name : ''
    },
    // 基本信息
    getDetail (data, flag) {
      const _this = this
      this.spinning = true
      allocateReturnQueryBySn({ allocateReturnSn: data.allocateReturnSn }).then(res => {
        if (res.status == 200) {
          if (flag) {
            _this.isShow = false
            _this.$emit('ok', res.data)
          }
        }
        this.spinning = false
      })
    },
    //  保存
    handleSave () {
      const _this = this
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          const form = JSON.parse(JSON.stringify(_this.form))
          _this.spinning = true
          allocateReturnSave(form).then(res => {
            if (res.status == 200) {
              _this.$message.success(res.message)
              _this.getDetail(res.data, true)
            } else {
              _this.spinning = false
            }
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 调往对象  change
    targetTypeChange (val) {
      console.log(val)
      this.$refs.ruleForm.resetFields()
      this.form.targetSn = undefined
      this.form.targetName = ''
      this.form.targetType = val
      if (val !== 'DEALER') {
        this.form.grabFlag = '0'
      }
    },
    resetForm () {
      this.$refs.ruleForm.resetFields()
      this.form = {
        targetType: 'DEALER',
        targetSn: undefined,
        targetName: '',
        costTypeSn: undefined,
        allocateTypeSn: undefined,
        allocateReturnTypeSn: undefined,
        grabFlag: '1',
        remarks: ''
      }
      this.allocateTypeVal = []
    }
  },
  watch: {
    //  父页面传过来的弹框状态
    openModal (newValue, oldValue) {
      this.isShow = newValue
    },
    //  重定义的弹框状态
    isShow (newValue, oldValue) {
      if (!newValue) {
        this.resetForm()
        this.$emit('close')
      }
    }
  }
}
</script>

<style lang="less">
.allocateBill-basicInfo-modal {
	.ant-modal-body {
		padding: 40px 40px 24px;
	}
	.btn-cont {
		text-align: center;
		margin: 35px 0 10px;
	}
}
</style>
