<template>
  <a-modal
    v-model="opened"
    :title="title"
    centered
    :maskClosable="false"
    :confirmLoading="confirmLoading"
    :width="560"
    :footer="null"
    @cancel="cancel"
  >
    <a-spin :spinning="spinning" tip="Loading...">
      <a-form-model
        id="chooseCustom-form"
        ref="ruleForm"
        :model="form"
        :rules="rules"
        :label-col="formItemLayout.labelCol"
        :wrapper-col="formItemLayout.wrapperCol"
      >
        <a-row :gutter="15">
          <a-col :span="20">
            <a-form-model-item label="客户名称" prop="buyerSn">
              <a-select
                show-search
                id="chooseCustom-buyerSn"
                v-model="form.buyerSn"
                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>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row :gutter="15">
          <a-col :span="20">
            <a-form-model-item label="是否同步" prop="syncFlag">
              <v-select
                code="FLAG"
                showType="radio"
                id="chooseCustom-syncFlag"
                v-model="form.syncFlag"
                allowClear
                placeholder="请选择"></v-select>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row :gutter="15">
          <a-col :span="20">
            <a-form-model-item label="退货仓库" prop="warehouseSn">
              <warehouse
                v-model="form.warehouseSn"
                showDef
                id="chooseCustom-basicInfo-warehouseSn"
                placeholder="请选择退货仓库"
              />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row :gutter="15">
          <a-col :span="20">
            <a-form-model-item label="退货类别" prop="goodFlag">
              <v-select
                code="GOOD_FLAG"
                showType="radio"
                id="chooseCustom-goodFlag"
                v-model="form.goodFlag"
                allowClear
                placeholder="请选择退货类别"></v-select>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-form-model-item :wrapper-col="{ span: 12, offset: 6 }" style="text-align: center;">
          <a-button @click="cancel" style="margin-right: 15px" id="chooseCustom-btn-back">取消</a-button>
          <a-button type="primary" :loading="confirmLoading" @click="handleSubmit" id="chooseCustom-btn-submit">保存</a-button>
        </a-form-model-item>
      </a-form-model>
    </a-spin>
  </a-modal>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import { VSelect } from '@/components'
import debounce from 'lodash/debounce'
import warehouse from '@/views/common/chooseWarehouse.js'
import { dealerSubareaScopeList, dealerDetailBySn } from '@/api/dealer'
import { getDefaultWarehouse } from '@/api/warehouse'
import { salesReturnInsert } from '@/api/salesReturn'
export default {
  name: 'SalesReturnChooseCustomModal',
  mixins: [commonMixin],
  components: { VSelect, warehouse },
  props: {
    show: [Boolean]
  },
  data () {
    this.lastFetchId = 0
    this.fetchUser = debounce(this.fetchUser, 800)
    return {
      opened: this.show,
      spinning: false,
      title: '新增销售退货单——选择客户',
      confirmLoading: false,
      formItemLayout: {
        labelCol: { span: 6 },
        wrapperCol: { span: 18 }
      },
      form: {
        salesReturnBillSource: 'SALES',
        buyerName: '', // 客户名称
        buyerSn: undefined, // 客户sn
        contactTel: '', //  联系电话
        contactName: '', //  联系人
        provinceSn: '', //  省
        provinceName: '',
        citySn: '', // 市
        cityName: '',
        countySn: '', // 区
        countyName: '',
        customerAddr: '', //  详细地址
        warehouseSn: undefined, // 退货仓库
        syncFlag: undefined, // 是否同步
        goodFlag: undefined
      },
      rules: {
        buyerSn: [{ required: true, message: '请选择客户', trigger: ['change', 'blur'] }],
        warehouseSn: [{ required: true, message: '请选择退货仓库', trigger: 'change' }],
        syncFlag: [{ required: true, message: '请选择是否同步', trigger: ['change', 'blur'] }],
        goodFlag: [{ required: true, message: '请选择退货类别', trigger: ['change', 'blur'] }]
      },
      fetching: false,
      dealerData: []
    }
  },
  methods: {
    fetchUser (dealerName) {
      if (dealerName == '') return
      this.lastFetchId += 1
      const fetchId = this.lastFetchId
      this.dealerData = []
      this.fetching = true
      dealerSubareaScopeList({ nameLike: dealerName.replace(/\s+/g, ''), pageNo: 1, pageSize: 20 }).then(res => {
        if (fetchId !== this.lastFetchId) {
          return
        }
        this.dealerData = res.data && res.data.list ? res.data.list : []
        this.fetching = false
      })
    },
    // 客户  change
    handleChange (value) {
      dealerDetailBySn({ sn: this.form.buyerSn }).then(res => {
        if (res.data) {
          const data = res.data
          this.form = Object.assign(this.form, {
            buyerName: data.dealerName, // 客户名称
            buyerSn: data.dealerSn, // 客户sn
            contactTel: data.contactMobile, //  联系电话
            contactName: data.contact, //  联系人
            provinceSn: data.provinceSn, //  省
            provinceName: data.provinceName,
            citySn: data.citySn, // 市
            cityName: data.cityName,
            countySn: data.districtSn, // 区
            countyName: data.districtName,
            customerAddr: data.address //  详细地址
          })
          console.log(this.form)
        } else {
          this.$message.error('获取客户信息失败')
        }
      })
    },
    //  保存
    handleSubmit (e) {
      e.preventDefault()
      const _this = this
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          // 保存销售单
          _this.salesSaveFun()
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 新建销售退货单
    salesSaveFun () {
      const _this = this
      const form = this.form
      console.log(form, 'save data')
      _this.spinning = true
      salesReturnInsert(form).then(res => {
        if (res.status == 200) {
          _this.$message.success(res.message)
          _this.$emit('ok', res.data)
          _this.cancel()
          _this.spinning = false
        } else {
          _this.spinning = false
        }
      })
    },
    getDefaultWarehouse () {
      getDefaultWarehouse().then(res => {
        this.form.warehouseSn = res.data ? res.data.warehouseSn : undefined
      })
    },
    cancel () {
      this.opened = false
      this.form = {
        salesReturnBillSource: 'SALES',
        buyerName: '', // 客户名称
        buyerSn: undefined, // 客户sn
        contactTel: '', //  联系电话
        contactName: '', //  联系人
        provinceSn: '', //  省
        provinceName: '',
        citySn: '', // 市
        cityName: '',
        countySn: '', // 区
        countyName: '',
        customerAddr: '', //  详细地址
        warehouseSn: undefined,
        syncFlag: undefined, // 是否同步
        goodFlag: undefined
      }
      this.$refs.ruleForm.resetFields()
      this.dealerData = []
      this.$emit('cancel')
    }
  },
  watch: {
    show (newValue, oldValue) {
      this.opened = newValue
      if (newValue) {
        this.getDefaultWarehouse()
      }
    }
  }
}
</script>
