<template>
  <a-modal
    centered
    class="dsModal-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="dsModal-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 id="dsModal-receiverSn" 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 id="dsModal-addressVal" 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="dsModal-sendNo"
              :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="dsModal-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" id="dsModal-printStatus">
              <a-radio value="NO_PRINT" id="dsModal-printStatus-1">
                允许打印
              </a-radio>
              <a-radio value="UNABLE_PRINT" id="dsModal-printStatus-2">
                暂不打印
              </a-radio>
              <a-radio value="CANCEL_PRINT" id="dsModal-printStatus-3">
                取消打印
              </a-radio>
            </a-radio-group>
          </a-form-model-item>
          <a-form-model-item label="新客户首笔订单" prop="newCustFlag">
            <a-radio-group v-model="form.newCustFlag" :disabled="!editFlag" id="dsModal-newCustFlag">
              <a-radio value="1" id="dsModal-newCustFlag-1">
                是
              </a-radio>
              <a-radio value="0" id="dsModal-newCustFlag-2">
                否
              </a-radio>
            </a-radio-group>
          </a-form-model-item>
        </a-form-model>
        <div class="btn-cont">
          <a-button id="dsModal-back" @click="isShow = false">取消下推</a-button>
          <a-button type="primary" id="dsModal-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 '../salesQueryNew/receivingAddress/chooseAddressModal.vue'
import dealerSubareaScopeList from '@/views/common/dealerSubareaScopeList.vue'
import { dealerRecevieAddrQuery } from '@/api/dealerRecevieAddr'
import { dealerNewLogEditFlag } from '@/api/dealearNewLog'
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: '', // 收货客户sn
        receiverName: '', // 收货客户名称
        dealerRecevieAddressSn: '', // 地址sn
        explainInfo: '', // 备注
        newCustFlag: undefined // 新客户首笔订单
      },
      rules: {
        sendNo: [{ required: true, message: '请输入发货编号', trigger: 'change' }],
        printStatus: [{ required: true, message: '请选择备货打印', trigger: 'change' }],
        newCustFlag: [{ required: true, message: '请选择是否新客户首笔订单', trigger: 'change' }],
        dealerRecevieAddressSn: [ { required: true, message: '请选择收货地址', trigger: 'change' } ]
      },
      detailData: null, //  详情数据
      addressVal: '选择地址', //  选择地址/更换地址
      chooseAddr: '', //  当前已选地址信息
      openAddrModal: false, // 选择地址弹框是否显示
      addressId: undefined, // 地址id
      receiverDisabled: false, // 是否选择收货客户名称
      editFlag: true
    }
  },
  methods: {
    // 设置发货编号
    setSendNo (i) {
      this.form.sendNo = i
      this.$refs.ruleForm.validateField('sendNo')
    },
    // 选择收货客户名称
    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) {
      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 || '')
        }
      }
    },
    getEditFlag () {
      dealerNewLogEditFlag({ sn: this.detailData.buyerSn }).then(res => {
        if (res.status == 200) {
          this.editFlag = res.data
          if (!this.editFlag) {
            this.form.newCustFlag = '0'
          } else {
            this.form.newCustFlag = undefined
          }
        }
      })
    },
    // 重置表单
    resetForm () {
      this.detailData = null
      this.$refs.ruleForm.resetFields()
      this.form = {
        sendNo: '',
        printStatus: undefined,
        buyerName: '',
        receiverSn: '',
        receiverName: '',
        dealerRecevieAddressSn: '',
        explainInfo: '',
        newCustFlag: undefined
      }
      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()
      } else {
        this.getEditFlag()
      }
    }
  }
}
</script>

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