<template>
  <a-modal
    centered
    class="purchaseOrder-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="purchaseOrder-basicInfo-form"
        ref="ruleForm"
        :model="form"
        :rules="rules"
        :label-col="formItemLayout.labelCol"
        :wrapper-col="formItemLayout.wrapperCol" >
        <a-form-model-item label="供应商" prop="purchaseTargetSn">
          <a-radio-group
            name="radioGroup"
            v-model="form.purchaseTargetSn"
            @change="tragetTypeChange"
            v-if="purchaseTragetType.length"
            id="purchaseOrder-basicInfo-purchaseTargetSn" >
            <a-radio v-for="item in purchaseTragetType" :key="item.purchaseTargetSn" :value="item.purchaseTargetSn" class="radio-s">{{ item.purchaseTargetName }}</a-radio>
          </a-radio-group>
          <span v-else>没有可选择的供应商</span>
        </a-form-model-item>
        <a-form-model-item label="支付方式" prop="settleStyleSn">
			  <v-select
			  code="SETTLE_STYLE" 
			  id="purchaseOrder-basicInfo-settleStyleSn" 
			  v-model="form.settleStyleSn" 
			  allowClear 
			  placeholder="请选择支付方式" 
			  ></v-select>
        </a-form-model-item>
        <a-form-model-item label="收货地址" prop="consigneeTel">
          {{ chooseAddr }}
          <a-button type="link" id="purchaseOrder-basicInfo-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 type="primary" :loading="confirmLoading" @click="handleSubmit" id="chooseCustom-btn-submit">保存</a-button>
          <a-button @click="isShow=false" style="margin-left: 15px" id="chooseCustom-btn-back">取消</a-button>
        </a-form-model-item>
      </a-form-model>
    </a-spin>
    <!-- 选择地址 -->
    <choose-address-modal :openModal="openAddrModal" @ok="handleOk" @verify="verifyFun" @close="openAddrModal=false" />
  </a-modal>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import { VSelect } from '@/components'
import chooseAddressModal from './receivingAddress/chooseAddressModal.vue'
import { shippingAddressQuery } from '@/api/shippingAddress'
import { purchaseSave, purchaseTargetList } from '@/api/purchase'
export default {
  name: 'BasicInfoModal',
  components: { VSelect, chooseAddressModal },
  mixins: [commonMixin],
  props: {
    openModal: { //  弹框显示状态
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      spinning: false,
      confirmLoading: false,
      isShow: this.openModal, //  是否打开弹框
      formItemLayout: {
        labelCol: { span: 4 },
        wrapperCol: { span: 18 }
      },
      form: {
        purchaseTargetType: '', // 供应商
        shippingAddressProvinceName: '', // 省
        shippingAddressCityName: '', // 市
        shippingAddressCountyName: '', // 区
        shippingAddress: '', // 详细地址
        consigneeTel: '', // 联系电话
        consigneeName: '', // 联系人名称
        settleStyleSn: undefined, //  支付方式
        purchaseTargetSn: undefined,
        purchaseTargetName: ''
      },
      rules: {
        purchaseTargetSn: [
          { required: true, message: '请选择供应商', trigger: 'change' }
        ],
        settleStyleSn: [
          { required: true, message: '请选择支付方式', trigger: 'change' }
        ],
        consigneeTel: [
          { required: true, message: '请选择收货地址(联系电话不能为空)', trigger: 'change' }
        ]
      },
      purchaseTragetType: [],
      addressVal: '选择地址', //  选择地址/更换地址
      chooseAddr: '', //  当前已选地址信息
      addressId: undefined,
      openAddrModal: false // 选择地址弹框是否显示
    }
  },
  methods: {
    resetForm () {
      this.$refs.ruleForm.resetFields()
      this.chooseAddr = ''
      this.addressVal = '选择地址'
      this.form.shippingAddressProvinceName = ''// 省
      this.form.shippingAddressCityName = '' // 市
      this.form.shippingAddressCountyName = '' // 区
      this.form.shippingAddress = ''// 详细地址
      this.form.consigneeTel = '' // 联系电话
      this.form.consigneeName = ''
      this.form.purchaseTargetType = ''
      this.form.purchaseTargetSn = undefined
      this.form.purchaseTargetName = ''
    },
    // 供应商change
    tragetTypeChange (e) {
      const val = e.target.value
      const ind = this.purchaseTragetType.findIndex(item => item.purchaseTargetSn == val)
      if (ind != -1) {
        this.form.purchaseTargetType = this.purchaseTragetType[ind].purchaseTargetType
        this.form.purchaseTargetName = this.purchaseTragetType[ind].purchaseTargetName
      }
    },
    //  保存
    handleSubmit (e) {
      e.preventDefault()
      const _this = this
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          if (_this.form.consigneeTel == '') {
            _this.$message.info('请选择收货地址')
            return false
          }
          _this.spinning = true
          purchaseSave(_this.form).then(res => {
            if (res.status == 200) {
              _this.isShow = false
              _this.$emit('ok', res.data)
              _this.spinning = false
              _this.$message.info(res.message)
            } else {
              _this.spinning = false
            }
          })
        } else {
          return false
        }
      })
    },
    //  选择地址
    handleChoose () {
      this.openAddrModal = true
    },
    //  地址保存
    handleOk (data) {
      this.chooseAddr = (data.consigneeName || '') + '（' + (data.consigneeTel || '--') + '）' + ' ' + (data.address || '')
      this.addressVal = '更换地址'
      this.form.shippingAddressProvinceName = data.provinceName // 省
      this.form.shippingAddressCityName = data.cityName // 市
      this.form.shippingAddressCountyName = data.countyName // 区
      this.form.shippingAddress = data.addr// 详细地址
      this.form.consigneeTel = data.consigneeTel // 联系电话
      this.form.consigneeName = data.consigneeName
      this.openAddrModal = false
    },
    // 编辑信息
    setData (data) {
      this.form = JSON.parse(JSON.stringify(data))
      this.chooseAddr = data.consigneeName + '（' + (data.consigneeTel || '--') + '）' + ' ' + data.shippingAddressProvinceName + '-' + data.shippingAddressCityName + '-' + data.shippingAddressCountyName + ' ' + data.shippingAddress
      this.addressVal = '更换地址'
    },
    getParentDealer () {
      const zb = this.$hasPermissions('B_SUPPLIER_ZB')
      const sj = this.$hasPermissions('B_SUPPLIER_SJ')
      let params = {}
      // 只能向上级采购
      if (sj) {
        params.purchaseTargetType = 'DEALER_UP'
      }
      // 只能向总部采购
      if (zb) {
        params.purchaseTargetType = 'SUPPLIER_SYS'
      }
      // 总部和上级都可以
      if (sj && zb) {
        params = {}
      }
      purchaseTargetList(params).then(res => {
        if (res.status == 200 && res.data[0]) {
          this.purchaseTragetType = res.data
        } else {
          this.purchaseTragetType = []
        }
      })
    },
    // 获取默认地址
    getDefaultAddress () {
      shippingAddressQuery({ defaultFlag: 1 }).then(res => {
        if (res.status == 200) {
          if (res.data.length == 1) {
            res.data[0].address = ''
            if (res.data[0].provinceName) {
              res.data[0].address += res.data[0].provinceName + '-'
            }
            if (res.data[0].cityName) {
              res.data[0].address += res.data[0].cityName + '-'
            }
            if (res.data[0].countyName) {
              res.data[0].address += res.data[0].countyName + '-'
            }
            res.data[0].address += res.data[0].addr
            this.addressId = res.data[0].id || undefined
            this.handleOk(res.data[0])
          }
        }
      })
    },
    verifyFun (id) {
      if (id == this.addressId) {
        this.chooseAddr = ''
        this.addressVal = '选择地址'
        this.form.shippingAddressProvinceName = ''// 省
        this.form.shippingAddressCityName = '' // 市
        this.form.shippingAddressCountyName = '' // 区
        this.form.shippingAddress = ''// 详细地址
        this.form.consigneeTel = '' // 联系电话
        this.form.consigneeName = ''
      }
    }
  },
  watch: {
    //  父页面传过来的弹框状态
    openModal (newValue, oldValue) {
      this.isShow = newValue
    },
    //  重定义的弹框状态
    isShow (newValue, oldValue) {
      if (!newValue) {
        this.$emit('close')
        this.resetForm()
      } else {
        this.getParentDealer()
        this.getDefaultAddress()
      }
    }
  }
}
</script>

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