<template>
  <a-modal
    v-model="opened"
    :title="title"
    centered
    :maskClosable="false"
    :confirmLoading="confirmLoading"
    :width="800"
    :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-form-model-item label="客户名称" prop="buyerSn">
          <dealerSubareaScopeList ref="dealerSubareaScopeList" id="chooseCustom-buyerSn" defValKey="buyerSn" @change="custChange" v-model="form.buyerSn" />
        </a-form-model-item>
        <a-form-model-item label="支付方式" prop="settleStyleSn">
          <v-select
            code="SETTLE_STYLE"
            id="chooseCustom-settleStyleSn"
            v-model="form.settleStyleSn"
            allowClear
            placeholder="请选择支付方式"></v-select>
        </a-form-model-item>
        <a-form-model-item prop="consigneeTel">
          <span slot="label">收货地址</span>
          {{ chooseAddr }}
          <a-button type="link" :disabled="!form.buyerSn" id="chooseCustom-chooseAddr" @click="handleChoose">{{ addressVal }} >></a-button>
        </a-form-model-item>
        <a-form-model-item :wrapper-col="{ span: 12, offset: 6 }" style="text-align: center;">
          <a-button @click="cancel" id="chooseCustom-btn-back">取消</a-button>
          <a-button type="primary" style="margin-left: 15px" :loading="confirmLoading" @click="handleSubmit" id="chooseCustom-btn-submit">保存</a-button>
        </a-form-model-item>
      </a-form-model>
    </a-spin>
    <!-- 选择地址 -->
    <choose-address-modal :openModal="openAddrModal" :paramsData="form.buyerSn" @ok="handleOk" @verify="verifyFun" @close="openAddrModal=false" />
  </a-modal>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import { VSelect } from '@/components'
import dealerSubareaScopeList from '@/views/common/dealerSubareaScopeList.vue'
import chooseAddressModal from './receivingAddress/chooseAddressModal.vue'
import { dealerRecevieAddrQuery } from '@/api/dealerRecevieAddr'
import chooseWarehouse from '@/views/common/chooseWarehouse'
import { salesSave } from '@/api/salesNew'
export default {
  name: 'SalesChooseCustomModal',
  mixins: [commonMixin],
  components: { VSelect, dealerSubareaScopeList, chooseAddressModal, chooseWarehouse },
  props: {
    show: [Boolean]
  },
  data () {
    return {
      opened: this.show,
      spinning: false,
      title: '选择客户', // 弹框标题
      confirmLoading: false, // loading
      // 表单列
      formItemLayout: {
        labelCol: { span: 4 },
        wrapperCol: { span: 18 }
      },
      // 表单数据
      form: {
        buyerSn: undefined, // 客户sn
        buyerName: '', // 客户名称
        settleStyleSn: undefined, // 支付方式
        shippingAddrProvinceSn: '',
        shippingAddrProvinceName: '', // 省
        shippingAddrCitySn: '',
        shippingAddrCityName: '', // 市
        shippingAddrCountySn: '',
        shippingAddrCountyName: '', // 区
        shippingAddr: '', // 详细地址
        consigneeTel: '', // 联系电话
        consigneeName: '', // 联系人名称
        warehouseSn: undefined // 仓库
      },
      // 表单校验规则
      rules: {
        buyerSn: [ { required: true, message: '请选择客户', trigger: ['change', 'blur'] } ],
        settleStyleSn: [ { required: true, message: '请选择支付方式', trigger: ['change', 'blur'] } ],
        consigneeTel: [ { required: true, message: '请选择收货地址', trigger: ['change', 'blur'] } ]
      },
      addressVal: '选择地址', //  选择地址/更换地址
      chooseAddr: '', //  当前已选地址信息
      openAddrModal: false // 选择地址弹框是否显示
    }
  },
  methods: {
    // 选择客户 change
    custChange (val) {
      if (val && val.key) {
        this.form.buyerSn = val.key || undefined
        this.form.buyerName = val.name || ''
        this.$refs.ruleForm.clearValidate()
        this.getDefaultAddress()
        if (val.row) {
          // this.form.warehouseSn = val.row.defaultWarehouseSn
        }
      } else {
        this.form.buyerName = ''
        this.form.buyerSn = undefined
        this.form.warehouseSn = undefined
        this.verifyFun(this.addressId)
      }
    },
    // 打开选择地址弹框
    handleChoose () {
      this.openAddrModal = true
    },
    // 保存
    handleSubmit (e) {
      e.preventDefault()
      const _this = this
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          _this.salesSaveFun()
        } else {
          return false
        }
      })
    },
    // 新建或编辑销售单
    salesSaveFun () {
      const _this = this
      const form = this.form
      _this.spinning = true
      salesSave(form).then(res => {
        if (res.status == 200) {
          _this.$message.success(res.message)
          _this.$emit('ok', res.data)
          if (_this.form.id) {
            _this.$emit('updateData')
          }
          _this.cancel()
          _this.spinning = false
        } else {
          _this.spinning = false
        }
      })
    },
    // 关闭弹框
    cancel () {
      this.opened = false
      this.$emit('cancel')
      this.$refs.ruleForm.resetFields()
    },
    // 地址保存
    handleOk (data) {
      this.chooseAddr = (data.consigneeName || '') + '（' + (data.consigneeTel || '-') + '）' + ' ' + (data.address || '')
      this.addressVal = '更换地址'
      this.form.shippingAddrProvinceSn = data.provinceSn || ''
      this.form.shippingAddrProvinceName = data.provinceName || '' // 省
      this.form.shippingAddrCitySn = data.citySn || ''
      this.form.shippingAddrCityName = data.cityName || '' // 市
      this.form.shippingAddrCountySn = data.countySn || ''
      this.form.shippingAddrCountyName = data.countyName || '' // 区
      this.form.shippingAddr = data.addr || ''// 详细地址
      this.form.consigneeTel = data.consigneeTel || '' // 联系电话
      this.form.consigneeName = data.consigneeName || ''
      this.addressId = data.id || undefined
      this.openAddrModal = false
      // 移除表单项的校验结果
      this.$refs.ruleForm.clearValidate('consigneeTel')
    },
    // 重置地址
    verifyFun (id) {
      if (id == this.addressId) {
        this.chooseAddr = ''
        this.addressVal = '选择地址'
        this.form.shippingAddrProvinceSn = ''
        this.form.shippingAddrProvinceName = ''// 省
        this.form.shippingAddrCitySn = ''
        this.form.shippingAddrCityName = '' // 市
        this.form.shippingAddrCountySn = ''
        this.form.shippingAddrCountyName = '' // 区
        this.form.shippingAddr = ''// 详细地址
        this.form.consigneeTel = '' // 联系电话
        this.form.consigneeName = ''
      }
    },
    // 获取默认地址
    getDefaultAddress () {
      dealerRecevieAddrQuery({ defaultFlag: 1, dealerSn: this.form.buyerSn }).then(res => {
        if (res.status == 200) {
          if (res.data.length == 1) {
            const ret = res.data[0]
            ret.address = (ret.provinceName ? (ret.provinceName + '-') : '') + (ret.cityName ? (ret.cityName + '-') : '') + (ret.countyName ? (ret.countyName + '-') : '') + ret.addr
            this.addressId = ret.id || undefined
            this.handleOk(ret)
          } else {
            this.verifyFun(this.addressId)
          }
        }
      })
    }
  },
  watch: {
    show (newValue, oldValue) {
      this.opened = newValue
      if (!newValue) {
        this.$refs.dealerSubareaScopeList.resetForm()
        this.$refs.ruleForm.resetFields()
        this.verifyFun(this.addressId)
      }
    }
  }
}
</script>
