<template>
  <a-modal
    centered
    class="dealerAccountEdit-modal"
    :footer="null"
    :maskClosable="false"
    :title="title"
    v-model="isShow"
    @cancel="isShow=false"
    :width="800">
    <!-- 表单 -->
    <div>
      <a-spin :spinning="spinning" tip="Loading...">
        <a-form-model
          id="dealerAccountEdit-form"
          ref="ruleForm"
          :model="form"
          :rules="rules"
          :label-col="formItemLayout.labelCol"
          :wrapper-col="formItemLayout.wrapperCol"
        >
          <a-form-model-item label="客户名称">
            <span>{{ detailData ? detailData.buyerName : '--' }}</span>
          </a-form-model-item>
          <div v-if="!receiverDisabled">
            <a-form-model-item label="收货客户名称" extra="如果收货客户和下单客户相同，则不需要选择收货客户名称">
              <dealerSubareaScopeList ref="dealerSubareaScopeList" defValKey="buyerSn" @change="custChange" v-model="form.receiverSn" />
            </a-form-model-item>
            <a-form-model-item label="收货地址" prop="dealerRecevieAddressSn" v-if="form.receiverSn">
              <div style="display:flex;padding-top:6px;">
                <div style="width:80%;flex-grow:1;line-height: 24px;">{{ chooseAddr }}</div>
                <a-button size="small" type="link" @click="openAddrModal = true">{{ addressVal }} >></a-button>
              </div>
            </a-form-model-item>
          </div>
          <div v-else>
            <a-form-model-item label="收货客户名称" v-if="detailData&&detailData.receiverName">
              {{ detailData.receiverName }}
            </a-form-model-item>
            <a-form-model-item label="收货客户名称" v-else>
              --
            </a-form-model-item>
            <a-form-model-item label="收货地址">
              {{ chooseAddr }}
            </a-form-model-item>
          </div>
          <a-form-model-item label="发货编号" prop="sendNo">
            <a-input
              id="dealerAccountEdit-phone"
              :maxLength="10"
              v-model.trim="form.sendNo"
              placeholder="请输入发货编号"
              allowClear />
            <div style="height: 24px;line-height: normal;">
              常用：<a-button size="small" v-for="i in 5" @click="setSendNo(i)" type="link">{{ i }}</a-button>
            </div>
          </a-form-model-item>
          <a-form-model-item label="发货说明">
            <a-input
              id="dealerAccountEdit-explainInfo"
              type="textarea"
              :maxLength="100"
              v-model.trim="form.explainInfo"
              placeholder="请输入发货说明(最多100字符)"
              allowClear />
          </a-form-model-item>
          <a-form-model-item label="备货打印" prop="printStatus">
            <a-radio-group v-model="form.printStatus">
              <a-radio value="NO_PRINT">
                允许打印
              </a-radio>
              <a-radio value="UNABLE_PRINT">
                暂不打印
              </a-radio>
              <a-radio value="CANCEL_PRINT">
                取消打印
              </a-radio>
            </a-radio-group>
          </a-form-model-item>
        </a-form-model>
        <div class="btn-cont">
          <a-button id="dealerAccountEdit-back" @click="isShow = false">取消下推</a-button>
          <a-button type="primary" id="dealerAccountEdit-save" @click="handleSave" style="margin-left: 15px;">确定下推</a-button>
        </div>
      </a-spin>
      <!-- 选择地址 -->
      <choose-address-modal :openModal="openAddrModal" :paramsData="form.receiverSn" @ok="handleOk" @verify="verifyFun" @close="openAddrModal=false" />
    </div>
  </a-modal>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import chooseAddressModal from '../salesQuery/receivingAddress/chooseAddressModal.vue'
import dealerSubareaScopeList from '@/views/common/dealerSubareaScopeList.vue'
import { dealerRecevieAddrQuery } from '@/api/dealerRecevieAddr'
export default {
  name: 'DsModal',
  mixins: [commonMixin],
  components: { dealerSubareaScopeList, chooseAddressModal },
  props: {
    openModal: { //  弹框显示状态
      type: Boolean,
      default: false
    },
    title: {
      type: String,
      default: '下推销售单'
    }
  },
  data () {
    return {
      isShow: this.openModal, //  是否打开弹框
      spinning: false,
      formItemLayout: {
        labelCol: { span: 4 },
        wrapperCol: { span: 18 }
      },
      form: {
        sendNo: '',
        printStatus: undefined,
        buyerName: '',
        receiverSn: '',
        receiverName: '',
        dealerRecevieAddressSn: '', // 地址sn
        explainInfo: ''
      },
      rules: {
        sendNo: [{ required: true, message: '请输入发货编号', trigger: 'change' }],
        printStatus: [{ required: true, message: '请选择备货打印', trigger: 'change' }],
        dealerRecevieAddressSn: [ { required: true, message: '请选择收货地址', trigger: 'change' } ]
      },
      detailData: null, //  详情数据
      addressVal: '选择地址', //  选择地址/更换地址
      chooseAddr: '', //  当前已选地址信息
      openAddrModal: false, // 选择地址弹框是否显示
      addressId: undefined,
      receiverDisabled: false
    }
  },
  methods: {
    setSendNo (i) {
      this.form.sendNo = i
      this.$refs.ruleForm.validateField('sendNo')
    },
    // 客户 change
    custChange (val) {
      if (val && val.key) {
        this.form.receiverSn = val.key || undefined
        this.form.receiverName = val.name || ''
        this.$refs.ruleForm.clearValidate()
        this.getDefaultAddress()
      } else {
        this.form.receiverSn = undefined
        this.form.receiverName = ''
        this.verifyFun(this.addressId)
      }
    },
    // 获取默认地址
    getDefaultAddress () {
      dealerRecevieAddrQuery({ defaultFlag: 1, dealerSn: this.form.receiverSn }).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.handleOk(ret)
          } else {
            this.verifyFun(this.addressId)
          }
        }
      })
    },
    verifyFun (id) {
      if (id == this.addressId) {
        this.chooseAddr = ''
        this.addressVal = '选择地址'
        this.form.dealerRecevieAddressSn = ''
      }
    },
    //  保存
    handleSave () {
      const _this = this
      _this.$refs.ruleForm.validate(valid => {
        if (valid) {
          _this.form.buyerName = _this.detailData.buyerName
          const formData = JSON.parse(JSON.stringify(_this.form))
          _this.$emit('ok', formData)
          _this.isShow = false
        } else {
          return false
        }
      })
    },
    //  地址保存
    handleOk (data) {
      console.log(data, 'chooseAddr')
      this.chooseAddr = (data.consigneeName || '') + '（' + (data.consigneeTel || '-') + '）' + ' ' + (data.address || '')
      this.addressVal = '更换地址'
      this.form.dealerRecevieAddressSn = data.dealerRecevieAddressSn || ''
      this.addressId = data.id || undefined
      this.openAddrModal = false
      // 移除表单项的校验结果
      this.$refs.ruleForm.validateField('dealerRecevieAddressSn')
    },
    //  获取详情
    setDetail (data) {
      this.detailData = data
      if (data && data.dispatchBillCount * 1 > 0) {
        this.receiverDisabled = true
        this.form.receiverSn = data.receiverSn
        this.form.receiverName = data.receiverName
        if (data.salesBillExtEntity) {
          const address = (data.salesBillExtEntity.shippingAddrProvinceName ? (data.salesBillExtEntity.shippingAddrProvinceName + '-') : '') + (data.salesBillExtEntity.shippingAddrCityName ? (data.salesBillExtEntity.shippingAddrCityName + '-') : '') + (data.salesBillExtEntity.shippingAddrCountyName ? (data.salesBillExtEntity.shippingAddrCountyName + '-') : '') + data.salesBillExtEntity.shippingAddr
          this.chooseAddr = (data.salesBillExtEntity.consigneeName || '') + '（' + (data.salesBillExtEntity.consigneeTel || '-') + '）' + ' ' + (address || '')
        }
      }
    },
    // 重置表单
    resetForm () {
      this.detailData = null
      this.$refs.ruleForm.resetFields()
      this.form = {
        sendNo: '',
        printStatus: undefined,
        buyerName: '',
        receiverSn: '',
        receiverName: '',
        dealerRecevieAddressSn: '',
        explainInfo: ''
      }
      if (!this.receiverDisabled) {
        this.$refs.dealerSubareaScopeList.resetForm()
        this.verifyFun(this.addressId)
      }
    }
  },
  watch: {
    //  父页面传过来的弹框状态
    openModal (newValue, oldValue) {
      this.isShow = newValue
    },
    //  重定义的弹框状态
    isShow (newValue, oldValue) {
      if (!newValue) {
        this.$emit('close')
        this.resetForm()
      }
    }
  }
}
</script>

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