<template>
  <a-modal
    v-model="opened"
    :title="title"
    centered
    :maskClosable="false"
    :confirmLoading="confirmLoading"
    :width="960"
    :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="16">
            <a-form-model-item label="客户名称" prop="buyerSn" :labelCol="{ span: 3 }" :wrapperCol="{ span: 20 }">
              <custList ref="custList" :isValidateEnabled="true" @change="custChange" v-model="form.buyerSn"></custList>
            </a-form-model-item>
          </a-col>
          <!-- <a-col :span="16">
            <a-form-model-item>
              <a-button type="primary" class="button-primary" @click="openNewCust" icon="plus">新增</a-button>
              （点击新增按钮新增客户）
            </a-form-model-item>
          </a-col> -->
        </a-row>
        <a-row :gutter="15">
          <a-col :span="24">
            <a-form-model-item label="客户地址" required style="margin: 0;" :labelCol="{ span: 2 }" :wrapperCol="{ span: 22 }">
              <a-row :gutter="15">
                <!-- 客户地址 -->
                <a-col span="8">
                  <a-form-model-item prop="provinceSn">
                    <a-select id="chooseCustom-provinceSn" allowClear @change="getCityList" v-model="form.provinceSn" placeholder="请选择省">
                      <a-select-option v-for="item in addrProvinceList" :value="item.areaSn" :key="item.areaSn + 'a'">{{ item.name }}</a-select-option>
                    </a-select>
                  </a-form-model-item>
                </a-col>
                <a-col span="8">
                  <a-form-model-item prop="citySn">
                    <a-select id="chooseCustom-citySn" allowClear @change="getAreaList" v-model="form.citySn" placeholder="请选择市">
                      <a-select-option v-for="item in addrCityList" :value="item.areaSn" :key="item.areaSn + 'b'">{{ item.name }}</a-select-option>
                    </a-select>
                  </a-form-model-item>
                </a-col>
                <a-col span="8">
                  <a-form-model-item prop="countySn">
                    <a-select id="chooseCustom-countySn" allowClear @change="areaCharged" v-model="form.countySn" placeholder="请选择区/县">
                      <a-select-option v-for="item in addrDistrictList" :value="item.areaSn" :key="item.areaSn + 'c'">{{ item.name }}</a-select-option>
                    </a-select>
                  </a-form-model-item>
                </a-col>
              </a-row>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="详细地址" prop="customerAddr" :labelCol="{ span: 2 }" :wrapperCol="{ span: 22 }">
              <a-input
                id="chooseCustom-customerAddr"
                :maxLength="60"
                v-model.trim="form.customerAddr"
                placeholder="请输入详细地址(最多60个字符)"
                allowClear />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row :gutter="15">
          <a-col :span="8">
            <a-form-model-item label="联系人" prop="consigneeName">
              <a-input
                id="chooseCustom-consigneeName"
                :maxLength="30"
                v-model.trim="form.consigneeName"
                placeholder="请输入联系人(最多30个字符)"
                allowClear />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="联系电话" prop="contactTel">
              <a-input
                id="chooseCustom-contactTel"
                :maxLength="15"
                v-model.trim="form.contactTel"
                placeholder="请输入联系电话(最多15个字符)"
                allowClear />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="联系手机" prop="contactMobile">
              <a-input
                id="chooseCustom-contactMobile"
                :maxLength="11"
                v-model.trim="form.contactMobile"
                placeholder="请输入联系手机(最多11个字符)"
                allowClear />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row :gutter="15">
          <a-col :span="8">
            <a-form-model-item label="是否抓单" prop="grabFlag">
              <v-select code="FLAG" id="chooseCustom-grabFlag" v-model="form.grabFlag" allowClear placeholder="请选择"></v-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="开单人">{{ $store.state.user.info.userNameCN }}</a-form-model-item>
          </a-col>
        </a-row>
        <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="cancel" style="margin-left: 15px" id="chooseCustom-btn-back">取消</a-button>
        </a-form-model-item>
      </a-form-model>
      <!-- 新增客户 -->
      <a-modal
        v-model="isNewCust"
        title="新增客户"
        centered
        width="60%"
        :maskClosable="false"
        @cancel="cancelNewCust"
        :footer="null"
      >
        <CustomerManagementEdit ref="newCust" model="modal" @ok="newCustFun"></CustomerManagementEdit>
      </a-modal>
    </a-spin>
  </a-modal>
</template>

<script>
import { getArea } from '@/api/data'
import { custFindById, updateByCustomerSn } from '@/api/customer'
import { salesReturnSave } from '@/api/salesReturn'
import { VSelect } from '@/components'
import custList from '@/views/common/custList.vue'
import CustomerManagementEdit from '@/views/customerManagement/customerInfo/edit.vue'
export default {
  name: 'ChooseCustomModal',
  components: { VSelect, CustomerManagementEdit, custList },
  props: {
    show: [Boolean]
  },
  data () {
    return {
      spinning: false,
      opened: this.show,
      title: '选择客户',
      confirmLoading: false,
      formItemLayout: {
        labelCol: { span: 6 },
        wrapperCol: { span: 18 }
      },
      buyerSnBak: '', // 更改前客户sn备份
      form: {
        buyerName: '', // 客户名称
        buyerSn: undefined, // 客户sn
        contactTel: '', //  联系电话
        contactMobile: '',
        consigneeName: '', //  联系人
        priceType: '', // 价格类型
        provinceSn: undefined, //  省
        provinceName: '',
        citySn: undefined, // 市
        cityName: '',
        countySn: undefined, // 区
        countyName: '',
        customerAddr: '', //  详细地址
        grabFlag: '1' // 是否抓单
      },
      rules: {
        buyerSn: [
          { required: true, message: '请选择客户', trigger: ['change', 'blur'] }
        ],
        contactMobile: [{ required: false, pattern: /^\d{11}$/, message: '请输入正确的手机号', trigger: 'blur' }],
        provinceSn: [
          { required: true, message: '请选择省', trigger: 'change' }
        ],
        citySn: [
          { required: true, message: '请选择市', trigger: 'change' }
        ],
        countySn: [
          { required: true, message: '请选择区/县', trigger: 'change' }
        ],
        grabFlag: [
          { required: true, message: '请选择是否铺货出库', trigger: 'change' }
        ]
      },
      addrProvinceList: [], //  省下拉
      addrCityList: [], //  市下拉
      addrDistrictList: [], //  区下拉
      custId: undefined, // 客户id
      isEdit: false, //  是否编辑状态
      isChangeCust: false, // 是否更换客户
      interId: null,
      isNewCust: false // 是否新增客户
    }
  },
  methods: {
    openNewCust () {
      this.isNewCust = true
      setTimeout(() => {
        this.$refs.newCust.getBaseData()
      }, 500)
    },
    // 新建客户
    newCustFun (data) {
      console.log(data, this.isEdit)
      this.isNewCust = false
      // 更新客户信息
      this.$refs.custList.setData({ key: data.customerSn, label: data.customerName, row: data })
      this.custChange({ key: data.customerSn, label: data.customerName, row: data })
    },
    cancelNewCust () {
      this.isNewCust = false
      this.$refs.newCust.getBaseData()
    },
    // 客户 change
    custChange (obj) {
      const _this = this
      if (obj && obj.key) {
        const cust = obj.row
        this.form.buyerSn = cust.customerSn
        // 编辑
        if (this.isEdit) {
          this.$confirm({
            title: '提示',
            content: '更换客户后信息需要重新完善，确认要更换吗？',
            centered: true,
            onOk () {
              _this.custId = cust.id
              _this.form.buyerName = cust.customerName
              _this.getDetail()
            },
            onCancel () {
              _this.form.buyerSn = _this.buyerSnBak
            }
          })
        } else {
          _this.custId = cust.id
          _this.form.buyerName = cust.customerName
          _this.getDetail()
        }
      } else {
        this.$refs.ruleForm.resetFields()
        this.$refs.custList.resetForm()
      }
    },
    // 编辑客户信息
    editCust (data) {
      console.log(data)
      this.title = '编辑客户信息'
      this.isEdit = true
      if (data.provinceSn) { this.getArea('city', data.provinceSn) }
      if (data.citySn) { this.getArea('district', data.citySn) }
      this.form = Object.assign(this.form, data)
      this.buyerSnBak = this.form.buyerSn
    },
    //  获取详情
    getDetail () {
      custFindById({ id: this.custId }).then(res => {
        const data = res.data
        if (res.status == 200 && data) {
          if (data.provinceSn) { this.getArea('city', data.provinceSn) }
          if (data.citySn) { this.getArea('district', data.citySn) }
          this.form = Object.assign(this.form, {
            buyerName: data.customerName, // 客户名称
            buyerSn: data.customerSn, // 客户sn
            contactTel: data.contactTel, //  联系电话
            contactMobile: data.contactMobile,
            consigneeName: data.contactName, //  联系人
            provinceSn: data.provinceSn, //  省
            provinceName: data.provinceName,
            priceType: data.priceType,
            citySn: data.citySn, // 市
            cityName: data.cityName,
            countySn: data.countySn, // 区
            countyName: data.countyName,
            customerAddr: data.customerAddr, //  详细地址
            fax: data.fax //  客户传真
          })
        } else {
          this.$message.error('获取客户信息失败')
          this.$refs.ruleForm.resetFields()
        }
        this.$refs.ruleForm.clearValidate()
      })
    },
    // 保存客户信息
    handleSaveCust () {
      const params = {
        customerName: this.form.buyerName,
        customerSn: this.form.buyerSn,
        contactTel: this.form.contactTel, //  联系电话
        contactMobile: this.form.contactMobile,
        contactName: this.form.consigneeName, //  联系人
        provinceSn: this.form.provinceSn, //  省
        provinceName: this.form.provinceName,
        priceType: this.form.priceType,
        citySn: this.form.citySn, // 市
        cityName: this.form.cityName,
        countySn: this.form.countySn, // 区
        countyName: this.form.countyName,
        customerAddr: this.form.customerAddr //  详细地址
      }
      this.spinning = true
      updateByCustomerSn(params).then(res => {
        this.spinning = false
        if (res.status == 200) {
          // 保存销售单
          this.salesSaveFun()
          this.spinning = false
        } else {
          this.spinning = false
        }
      })
    },
    //  保存
    handleSubmit (e) {
      e.preventDefault()
      const _this = this
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          // 保存客户信息
          _this.handleSaveCust()
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 新建或编辑销售单
    salesSaveFun () {
      const _this = this
      const form = this.form
      _this.spinning = true
      salesReturnSave(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
        }
      })
    },
    cancel () {
      this.opened = false
      this.$refs.ruleForm.resetFields()
      this.$refs.custList.resetForm()
      this.$emit('cancel')
    },
    // 获取城市列表
    getCityList (val) {
      this.addrCityList = []
      this.addrDistrictList = []
      this.form.citySn = undefined
      this.form.cityName = ''
      this.form.countySn = undefined
      this.form.countyName = ''
      if (val) {
        this.getArea('city', val)
        this.form.provinceName = this.addrProvinceList.find(item => item.areaSn == val).name
      } else {
        this.form.provinceName = ''
      }
    },
    // 获取区县列表
    getAreaList (val) {
      this.addrDistrictList = []
      this.form.countySn = undefined
      this.form.countyName = ''
      if (val) {
        this.getArea('district', val)
        this.form.cityName = this.addrCityList.find(item => item.areaSn == val).name
      } else {
        this.form.cityName = ''
      }
    },
    // 区县变更
    areaCharged (val) {
      if (val) {
        this.form.countyName = this.addrDistrictList.find(item => item.areaSn == val).name
      } else {
        this.form.countyName = ''
      }
    },
    //  省/市/区
    getArea (leve, sn) {
      let params
      if (leve == 'province') {
        params = { type: '2' }
      } else {
        params = { parentId: sn, type: leve == 'city' ? '3' : '4' }
      }
      getArea(params).then(res => {
        if (res.status == 200) {
          if (leve == 'province') {
            this.addrProvinceList = res.data || []
          } else if (leve == 'city') {
            this.addrCityList = res.data || []
          } else if (leve == 'district') {
            this.addrDistrictList = res.data || []
          }
        } else {
          if (leve == 'province') {
            this.addrProvinceList = []
          } else if (leve == 'city') {
            this.addrCityList = []
          } else if (leve == 'district') {
            this.addrDistrictList = []
          }
        }
      })
    }
  },
  watch: {
    show (newValue, oldValue) {
      this.opened = newValue
      if (newValue) {
        this.getArea('province')
      }
    }
  }
}
</script>
