<template>
  <a-modal
    centered
    class="transferReturn-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="transferReturn-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="transferReturn-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="transferReturn-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" :id="'basicInfo-dealerName'+item.dealerSn" :key="item.dealerSn" :value="item.dealerSn">{{ item.dealerName }}</a-select-option>
          </a-select>
          <department
            v-else-if="isDepartment"
            id="transferReturn-basicInfo-targetSn"
            style="width: 100%;"
            placeholder="请选择部门"
            @change="departementChange"
            v-model="form.targetSn"></department>
          <a-input
            id="transferReturn-basicInfo-targetName"
            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="transferReturn-basicInfo-allocateTypeVal" 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="transferReturn-basicInfo-grabFlag"
            v-model="form.grabFlag"
            allowClear
            placeholder="请选择"></v-select>
        </a-form-model-item>
        <a-form-model-item label="调入仓库" prop="warehouseSn">
          <warehouse
            v-model="form.warehouseSn"
            id="transferReturn-basicInfo-warehouseSn"
            placeholder="请选择调入仓库"
          />
        </a-form-model-item>
        <a-form-model-item label="备注" prop="remark">
          <a-textarea id="transferReturn-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="transferReturn-basicInfo-modal-save" @click="handleSave">保存</a-button>
        <a-button id="transferReturn-basicInfo-modal-cancel" @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 department from '@/views/expenseManagement/expenseReimbursement/department.js'
import warehouse from '@/views/common/chooseWarehouse.js'
import AllocateType from '@/views/common/allocateType.js'
// 接口
import { dealerSubareaScopeList } from '@/api/dealer'
import { allocateReturnSave, allocateReturnQueryBySn } from '@/api/allocateReturn'
export default {
  name: 'TransferOutBasicInfoModal',
  components: { VSelect, AllocateType, department, warehouse },
  mixins: [commonMixin],
  props: {
    openModal: {
      //  弹框显示状态
      type: Boolean,
      default: false
    }
  },
  data () {
    this.fetchUser = debounce(this.fetchUser, 800)
    return {
      isShow: this.openModal, //  是否打开弹框
      spinning: false,
      // form表单label布局
      formItemLayout: {
        labelCol: { span: 4 },
        wrapperCol: { span: 20 }
      },
      allocateTypeVal: [], // 费用/调拨退货类型  下拉数据
      // 提交参数
      form: {
        targetType: 'DEALER', // 调往对象
        targetSn: undefined, // 调往对象sn
        targetName: '', // 调往对象名称
        costTypeSn: undefined, // 费用/调拨退货类型sn
        allocateSortSn: undefined, // 调拨对象sn
        allocateReturnTypeSn: undefined, // 调拨类别sn
        warehouseSn: undefined, // 出库仓库
        grabFlag: '1', // 是否抓单 1是 0否
        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' }],
        warehouseSn: [{ 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
      this.form.warehouseSn = this.dealerData[ind].defaultWarehouseSn
    },
    // 选择部门
    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.warehouse = undefined
      this.form.targetType = val
      this.form.grabFlag = val != 'DEALER' ? '0' : '1'
    },
    // 重置
    resetForm () {
      this.$refs.ruleForm.resetFields()
      this.form = {
        targetType: 'DEALER',
        targetSn: undefined,
        targetName: '',
        costTypeSn: undefined,
        allocateTypeSn: undefined,
        allocateReturnTypeSn: undefined,
        warehouse: 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">
.transferReturn-basicInfo-modal {
	.ant-modal-body {
		padding: 40px 40px 24px;
	}
	.btn-cont {
		text-align: center;
		margin: 35px 0 10px;
	}
}
</style>
