<template>
  <div class="customerManagementEdit-wrap">
    <a-page-header :ghost="false" :backIcon="false" v-if="model=='page'" class="customerManagementEdit-back">
      <!-- 自定义的二级文字标题 -->
      <template slot="subTitle">
        <a id="customerManagementEdit-back-btn" href="javascript:;" @click="handleBack"><a-icon type="left" /> 返回列表</a>
      </template>
    </a-page-header>
    <a-spin :spinning="spinning" tip="Loading...">
      <a-card size="small" :bordered="false" class="customerManagementEdit-table-page-wrapper">
        <a-form-model
          id="customerManagementEdit-form"
          ref="ruleForm"
          :model="form"
          :rules="rules"
          :label-col="formItemLayout.labelCol"
          :wrapper-col="formItemLayout.wrapperCol"
        >
          <a-row :gutter="15">
            <a-col :span="8">
              <a-form-model-item label="客户名称" prop="customerName">
                <a-input
                  id="customerManagementEdit-customerName"
                  :maxLength="30"
                  v-model.trim="form.customerName"
                  @change="filterEmpty"
                  placeholder="请输入客户名称(最多30个字符)"
                  allowClear />
              </a-form-model-item>
            </a-col>
            <a-col :span="8">
              <a-form-model-item label="联系电话" prop="contactTel">
                <a-input id="customerManagementEdit-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="customerManagementEdit-contactMobile" :maxLength="11" v-model.trim="form.contactMobile" placeholder="请输入联系手机(最多11个字符)" allowClear />
              </a-form-model-item>
            </a-col>
            <a-col :span="8">
              <a-form-model-item label="联系人" prop="contactName">
                <a-input id="customerManagementEdit-contactName" :maxLength="30" v-model.trim="form.contactName" placeholder="请输入联系人(最多30个字符)" allowClear />
              </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: 3 }" :wrapperCol="{ span: 20 }">
                <a-row :gutter="15">
                  <!-- 客户地址 -->
                  <a-col span="8">
                    <a-form-model-item prop="provinceSn">
                      <a-select id="customerManagementEdit-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="customerManagementEdit-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="customerManagementEdit-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: 3 }" :wrapperCol="{ span: 20 }">
                <a-input id="customerManagementEdit-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="fax">
                <a-input id="customerManagementEdit-fax" :maxLength="30" v-model.trim="form.fax" placeholder="请输入客户传真(最多30个字符)" allowClear />
              </a-form-model-item>
            </a-col>
            <a-col :span="8">
              <a-form-model-item label="配送方式" prop="dispatchType">
                <v-select
                  code="DISPATCH_TYPE"
                  id="customerManagementEdit-dispatchType"
                  v-model="form.dispatchType"
                  allowClear
                  placeholder="请选择配送方式"
                ></v-select>
              </a-form-model-item>
            </a-col>
            <a-col :span="8">
              <a-form-model-item label="是否卫星仓客户" prop="satelliteFlag">
                <span style="padding-left: 11px;">{{ form.satelliteFlag == 1 ? '是' : '否' }}</span>
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row :gutter="15">
            <a-col :span="8">
              <a-form-model-item label="价格类型" ref="priceType" prop="priceType">
                <v-select code="PRICE_TYPE" id="customerManagementEdit-priceType" v-model="form.priceType" allowClear placeholder="请选择价格类型" ></v-select>
              </a-form-model-item>
            </a-col>
            <a-col :span="8">
              <a-form-model-item label="收款方式" prop="settleStyleSn">
                <a-select id="customerManagementEdit-settleStyleSn" v-model="form.settleStyleSn" allowClear placeholder="请选择收款方式">
                  <a-select-option v-for="item in settleStyleList" :value="item.settleStyleSn" :key="item.settleStyleSn">{{ item.name }}</a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
            <a-col :span="8">
              <a-form-model-item label="客户类型" prop="customerTypeSn">
                <a-select id="customerManagementEdit-customerTypeSn" v-model="form.customerTypeSn" allowClear placeholder="请选择客户类型">
                  <a-select-option v-for="item in custTypeList" :value="item.customerTypeSn" :key="item.customerTypeSn">{{ item.name }}</a-select-option>
                </a-select>
              </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" @click="handleSubmit" size="large" id="customerManagementEdit-btn-submit" style="padding: 0 60px;">保存</a-button>
          </a-form-model-item>
        </a-form-model>
      </a-card>
    </a-spin>
  </div>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import { STable, VSelect } from '@/components'
import { getArea } from '@/api/data'
import { custSave, custFindById, settleStyleFindAllList } from '@/api/customer'
import { custTypeFindAllList } from '@/api/custType'
export default {
  name: 'CustomerManagementEdit',
  components: { STable, VSelect },
  mixins: [commonMixin],
  props: {
    model: {
      type: String,
      default: 'page'
    }
  },
  data () {
    return {
      spinning: false,
      formItemLayout: {
        labelCol: { span: 9 },
        wrapperCol: { span: 14 }
      },
      form: {
        id: null,
        customerName: '', // 客户名称
        contactTel: '', //  联系电话
        contactMobile: '', //  联系手机
        contactName: '', //  联系人
        provinceSn: undefined, //  省
        provinceName: '',
        citySn: undefined, // 市
        cityName: '',
        countySn: undefined, // 区
        countyName: '',
        customerAddr: '', //  详细地址
        fax: '', //  客户传真
        dispatchType: '', //  配送方式
        satelliteFlag: 0, //  是否卫星仓客户
        customerTypeSn: undefined, //  客户类型
        priceType: '', //  价格类型
        settleStyleSn: undefined //  收款方式
      },
      rules: {
        customerName: [{ required: true, message: '请输入客户名称', trigger: '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' }],
        priceType: [{ required: true, message: '请选择价格类型', trigger: 'change' }],
        settleStyleSn: [{ required: true, message: '请选择收款方式', trigger: 'change' }]
      },
      addrProvinceList: [], //  省下拉
      addrCityList: [], //  市下拉
      addrDistrictList: [], //  区下拉
      custTypeList: [], //  客户类型  下拉数据
      settleStyleList: [] //  收款方式  下拉数据
    }
  },
  methods: {
    filterEmpty () {
      let str = this.form.customerName
      str = str.replace(/\ +/g, '')
      str = str.replace(/[ ]/g, '')
      str = str.replace(/[\r\n]/g, '')
      this.form.customerName = str
    },
    //  获取客户信息
    getDetail () {
      custFindById({ id: this.$route.params.id }).then(res => {
        if (res.status == 200) {
          if (res.data.provinceSn) { this.getArea('city', res.data.provinceSn) }
          if (res.data.citySn) { this.getArea('district', res.data.citySn) }
          this.form = Object.assign(this.form, res.data)
        } else {
          this.$refs.ruleForm.resetFields()
        }
      })
    },
    //  客户类型
    getCustTypeList () {
      custTypeFindAllList().then(res => {
        if (res.status == 200) {
          this.custTypeList = res.data
        } else {
          this.custTypeList = []
        }
      })
    },
    // 收款方式
    getSettleStyleList () {
      settleStyleFindAllList().then(res => {
        if (res.status == 200) {
          this.settleStyleList = res.data
        } else {
          this.settleStyleList = []
        }
      })
    },
    //  保存
    handleSubmit (e) {
      e.preventDefault()
      const _this = this
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          const form = _this.form
          form.id = this.$route.params.id && this.model == 'page' ? this.$route.params.id : null
          _this.spinning = true
          custSave(form).then(res => {
            if (res.status == 200) {
              _this.$message.success(res.message)
              if (_this.model == 'page') {
                setTimeout(() => {
                  _this.handleBack()
                }, 600)
              } else {
                _this.$emit('ok', res.data)
              }
              _this.spinning = false
            } else {
              _this.spinning = false
            }
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    //  返回列表
    handleBack () {
      this.$router.push({ path: '/customerManagement/customerInfo/list' })
    },
    // 获取城市列表
    getCityList (val) {
      this.addrCityList = []
      this.addrDistrictList = []
      this.form.citySn = undefined
      this.form.countySn = undefined
      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
      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 = []
          }
        }
      })
    },
    // 获取基础数据
    getBaseData () {
      this.getArea('province') //  省市区
      this.getCustTypeList() //  客户类型
      this.getSettleStyleList() // 收款方式
      this.$refs.ruleForm.resetFields()
    },
    initPage () {
      this.getBaseData()
      if (this.$route.params.id) {
        //  编辑页
        this.getDetail()
      }
    }
  },
  mounted () {
    if (!this.$store.state.app.isNewTab) { // 页签刷新时调用
      this.initPage()
    }
  },
  activated () {
    // 如果是新页签打开或者进入新的子页（例：存在列表第2条数据编辑页页签时再打开第4条数据的编辑页），则重置当前页面
    if (this.$store.state.app.isNewTab || !this.$store.state.app.isNewSubTab) {
      this.initPage()
    }
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {})
  }
}
</script>

<style lang="less">
.customerManagementEdit-wrap {
  height: 100%;
  >.ant-spin-nested-loading{
    height: calc(100% - 52px);
    .ant-spin-container{
      height: 97%;
    }
  }
	.customerManagementEdit-back {
		margin-bottom: 10px;
	}
  .customerManagementEdit-table-page-wrapper{
    height: 100%;
  }
}
</style>
