<template>
  <div class="p20">
    <el-form ref="ruleForm" :model="ruleForm" label-width="120px" :rules="rules" style="width:600px;">
      <el-form-item prop="contact" label="联系人">
        <el-input v-model="ruleForm.contact" class="w-360" :maxlength="20" show-word-limit placeholder="请输入联系人姓名"></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-input v-model="ruleForm.phone" type="text" class="w-360" placeholder="请输入手机号码">
          <el-select v-model="areaCode" slot="prepend" placeholder="请选择" style="width:100px">
            <el-option :label="`+` + `${item.code}`" :value="item.code" v-for="(item, index) in areaCodeList" :key="index"></el-option>
          </el-select>
        </el-input>
      </el-form-item>
      <el-form-item label="座机号">
        <el-input v-model="tel1" :maxlength="20" class="mr10" style="width:106px;" placeholder="区号"></el-input>
        <el-input v-model="tel2" :maxlength="20" class="mr10" style="width:128px;" placeholder="座机号"></el-input>
        <el-input v-model="tel3" :maxlength="20" style="width:106px;" placeholder="分机号(选填)"></el-input>
      </el-form-item>
      <el-form-item label="所在地区" prop="cityIds">
        <el-cascader v-model="cityIds" style="width:360px;" placeholder="请选择省/市/区" :options="cityList" @change="change"></el-cascader>
      </el-form-item>
      <el-form-item prop="address" label="详细地址">
        <el-input type="textarea" class="w-360" placeholder="请输入详细地址，如街道名称、门牌号等信息" v-model="ruleForm.address" :maxlength="50" show-word-limit></el-input>
      </el-form-item>
      <el-form-item prop="type" label="地址类型">
        <el-checkbox v-model="type" disabled class="special">退货地址</el-checkbox>
      </el-form-item>
      <el-form-item prop="defaultFlag">
        <el-checkbox v-model="flag" style="margin-left:20px;color:#303133" @change="changeFlag">设为默认退货地址</el-checkbox>
      </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 areaCodeList from '@/assets/areaCode.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,
      areaCodeList: areaCodeList,
      areaCode: '86',
      ruleForm: {
        type: 1,
        defaultFlag: 0,
        contact: '',
        phone: '',
        address: '',
      },
      rules: {
        contact: [ { required: true, message: '联系人不能为空', trigger: 'blur' } ],
        phone: [ { required: true, validator: phoneValidator, trigger: 'blur' } ],
        cityIds: [ { required: true, validator: cityValidator, trigger: 'change' } ],
        address: [ { required: true, message: '详细地址不能为空', trigger: 'blur' } ],
        tel: [ { validator: telValidator, trigger: 'blur' } ],
      },
      flag: false,
      type: true,
      tel1: '',
      tel2: '',
      tel3: '',
      cityIds: [],
      cityList
    };
  },
  mounted() {
    if(this.addressId) {
      this.getInfo();
    }
  },
  created() {
    this.$emit('updateBread', [ { breadName: '福利中心', breadPath: '/index' }, { breadName: '地址库管理', breadPath: '/setting/address-lib-list' }, { breadName: (this.addressId ? '编辑' : '新建') + '地址库' } ]);
  },
  methods: {
    change(value){
      console.log(value);
      // this.cityIds;
    },
    changeFlag(value){
      if(value){
        this.ruleForm.defaultFlag = 1;
      }else{
        this.ruleForm.defaultFlag = 0;
      }
    },
    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}` : '',
            areaNo: this.areaCode,
          };
          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.areaNo){
          this.areaCode = info.areaNo || '';
        }
        if(info.tel) {
          const tel = info.tel.split(',');
          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>
<style scoped>
.w-480 {
  width: 480px;
}
.w-360{
  width: 360px;
}
</style>
<style>
.special .el-checkbox__input.is-checked+.el-checkbox__label{
  color: #c4c6cf;
}
</style>
