<template>
  <div class="p20">
    <el-form ref="ruleForm" :model="ruleForm" label-width="120px" :rules="rules" style="width:600px;">
      <el-form-item prop="type" label="地址类型">
        <el-radio-group v-model="ruleForm.type">
        <el-radio :label="1">退货地址</el-radio>
      </el-radio-group>
      </el-form-item>
      <el-form-item prop="defaultFlag" label="是否默认">
        <el-switch :active-value="1" :inactive-value="0" v-model="ruleForm.defaultFlag"></el-switch>
      </el-form-item>
      <el-form-item prop="contact" label="联系人">
        <el-input v-model="ruleForm.contact" :maxlength="20" show-word-limit></el-input>
      </el-form-item>
      <el-form-item prop="phone" label="手机号">
        <dm-input-phone style="width:100%;" v-model="ruleForm.phone" show-word-limit></dm-input-phone>
      </el-form-item>
      <el-form-item prop="tel" label="电话">
        <el-input v-model="tel1" :maxlength="20" style="width:120px;" placeholder="请填写区号"></el-input><span class="ml5 mr5 gray02">-</span>
        <el-input v-model="tel2" :maxlength="20" style="width:120px;" placeholder="请填写座机号"></el-input><span class="ml5 mr5 gray02">-</span>
        <el-input v-model="tel3" :maxlength="20" style="width:120px;" placeholder="请填写分机号"></el-input>
      </el-form-item>
      <el-form-item prop="cityIds" label="所在地区">
        <el-cascader v-model="cityIds" style="width:100%;" :options="cityList"></el-cascader>
      </el-form-item>
      <el-form-item prop="address" label="详细地址">
        <el-input type="textarea" placeholder="请不要重复填写省市区" v-model="ruleForm.address" :maxlength="50" show-word-limit></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm()">{{ addressId ? '保存' : '确认新建' }}</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import api from '@/api/gift.js';
import cityList from '@/assets/city.json';
import { isEmpty } from '@/utils/index';
const { getAddressDetails, insertOrUpdateAddress } = api;
export default {
  data() {
    let phoneValidator = (rule, value, callback) => {
      let reg = /^1[34578]\d{9}$/;
      if (value !== '') {
        if (!reg.test(value)) {
          callback(new Error('手机号码不符合规则'));
        } else {
          callback();
        }
      } else {
        callback();
      }
    };
    let cityValidator = (rule, value, callback) => {
      if(this.cityIds.length == 0) {
        callback(new Error('请填写省市区'));
        return;
      }
      callback();
    };

    let telValidator = (rule, value, callback) => {
      const { tel1, tel2, tel3 } = this;
      const arr = [ tel1, tel2, tel3 ];
      if(arr.filter(v => isEmpty(v)).length == 3) {
        // 可以都不填
        callback();
        return;
      }
      if(arr.some(v => isEmpty(v))) {
        callback(new Error('电话填写不完整'));
        return;
      }
      if(arr.some(v => !/^[0-9]*$/.test(v))) {
        callback(new Error('请输入数字'));
        return;
      }
      callback();
    };
    return {
      loading: false,
      addressId: this.$route.query.id,
      ruleForm: {
        type: 1,
        defaultFlag: 0,
        contact: '',
        phone: '',
        address: ''
      },
      rules: {
        contact: [ { required: true, message: '联系人不能为空', trigger: 'blur' } ],
        phone: [ { validator: phoneValidator, trigger: 'blur' } ],
        cityIds: [ { required: true, validator: cityValidator, trigger: 'change' } ],
        address: [ { required: true, message: '详细地址不能为空', trigger: 'blur' } ],
        tel: [ { validator: telValidator, trigger: 'blur' } ],
      },
      tel1: '',
      tel2: '',
      tel3: '',
      cityIds: [],
      cityList
    };
  },
  mounted() {
    if(this.addressId) {
      this.getInfo();
    }
  },
  created() {
    this.$emit('updateBread', [  { breadName: '福利中心'  }, { breadName: '通用设置' }, { breadName: '地址库管理', breadPath: '/setting/address-lib-list' }, { breadName: (this.addressId ? '编辑' : '新建') + '地址库' } ]);
  },
  methods: {
    submitForm() {
      this.$refs.ruleForm.validate((valid) => {
        if (!valid) {
          return;
        } else {
          if (this.ruleForm.phone === '' && this.tel1 == '') {
            this.$message.error('手机号码和电话至少填写一个');
            return;
          }
          this.loading = true;
          const { type, defaultFlag, contact, phone, address } = this.ruleForm;
          let params = {
            type,
            defaultFlag,
            contact,
            phone,
            address,
            provinceId: this.cityIds[0],
            cityId: this.cityIds[1],
            countyId: this.cityIds[2],
            tel: this.tel1 ? `${this.tel1},${this.tel2},${this.tel3}` : ''
          };
          if(this.addressId) {
            params.addressId = this.addressId;
          }
          insertOrUpdateAddress(params).then(res => {
            this.loading = false;
            this.$tips({ message: '操作成功', type: 'success' });
            this.$router.push('/setting/address-lib-list');
          }).catch(() => {
            this.loading = false;
          });
        }
      });
    },
    getInfo() {
      this.loading = true;
      let params = {
        addressId: this.addressId
      };
      getAddressDetails(params).then(res => {
        const info = res.result || {};
        Object.keys(this.ruleForm).map(key => {
          if (key in res.result) {
            this.ruleForm[key] = info[key];
          }
        });
        if(info.tel) {
          const tel = info.tel.join(',');
          this.tel1 = tel[0];
          this.tel2 = tel[1];
          this.tel3 = tel[2];
        }
        this.cityIds = [ info.provinceId, info.cityId, info.countyId ];
        this.loading = false;
      }).catch(() => {
        this.loading = false;
      });
    },
  }
};
</script>
