<template>
  <div >
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="收货人姓名" prop="realName">
          <el-input v-model="form.realName" placeholder="请输入收货人姓名" />
        </el-form-item>
        <el-form-item label="收货人电话" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入收货人电话" />
        </el-form-item>
        <el-form-item label="收货地址" prop="district">
          <el-row :gutter="20">
          <el-col :span="6">
             <el-select @change="provinceChange" v-model="form.province" placeholder="请选择">
                <el-option
                  v-for="item in province"
                  :key="item.cityId"
                  :label="item.name"
                  :value="item.name">
                </el-option>
              </el-select>
          </el-col>
          <el-col :span="6">
            <el-select @change="cityChange" v-model="form.city" placeholder="请选择">
                <el-option
                  v-for="item in city"
                  :key="item.cityId"
                  :label="item.name"
                  :value="item.name">
                </el-option>
              </el-select>
          </el-col>
          <el-col :span="6">
             <el-select @change="districtChange" v-model="form.district" placeholder="请选择">
                <el-option
                  v-for="item in district"
                  :key="item.cityId"
                  :label="item.name"
                  :value="item.name">
                </el-option>
              </el-select>
          </el-col>
        </el-row>
        </el-form-item>
        <el-form-item label="详细地址" prop="detail">
          <el-input v-model="form.detail" placeholder="请输入收货人详细地址" />
        </el-form-item>
      </el-form>
      <div  style="text-align:right;">
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
  </div>
</template>

<script>
import { listUserAddress, getUserAddress, delUserAddress, addUserAddress, updateUserAddress, exportUserAddress } from "@/api/users/userAddress";
import {getCitys} from "@/api/hisStore/city";
export default {
  name: "add",
  data() {
    return {
      isEdit: false,
      editAddressId: null,
      citys:[],
      province:[],
      city:[],
      district:[],
      // 表单参数
      form: {
        userId: null,
        realName: null,
        phone: null,
        detail: null,
        province:null,
        city:null,
        district:null,
        cityId:null,
        isDefault: null,
      },
      // 表单校验
      rules: {
        userId: [
          { required: true, message: "会员不能为空", trigger: "blur" }
        ],
        realName: [
          { required: true, message: "姓名不能为空", trigger: "blur" }
        ],
        phone: [
          { required: true, message: "电话不能为空", trigger: "blur" }
        ],
        detail: [
          { required: true, message: "详细地址不能为空", trigger: "blur" }
        ],
        district: [
          { required: true, message: "收货地址不能为空", trigger: "blur" }
        ],

      }
    };
  },
  created(){
    this.getCityList();
  },
  methods: {
    districtChange(val){
      const item = this.district.find(i => i.name === val)
    },
    cityChange(val){
      const item = this.city.find(i => i.name === val)
      this.district = item.children || []
      this.form.district=null;
      this.form.cityId=item.cityId;
    },
    provinceChange(val){
      const item = this.citys.find(i => i.name === val)
      this.city = item.children || []
      this.district=[];
      this.form.city=null;
      this.form.district=null;
      this.form.cityId=null;
    },
    getCityList(){
      return getCitys().then(res => {
          this.loading = false;
          this.citys = this.convertCityData(res.data)
          this.province=this.citys.filter(item => item.parentId===0 )
        })
    },
    convertCityData(array) {
      return array.map(item => {
        return {
          'cityId': item.value,
          'name': item.label,
          'parentId':  item.pid,
          'children': item.children && this.convertCityData(item.children)
        }
      });
    },
    async init(userId, addressData){
      this.form.userId = userId;
      if (this.province.length === 0) {
        await this.getCityList();
      }
      this.$nextTick(() => {
        if (this.$refs["form"]) {
          this.$refs["form"].clearValidate();
        }
      });
      if (addressData) {
        this.isEdit = true;
        this.editAddressId = addressData.addressId;
        this.form.realName = addressData.realName;
        this.form.phone = addressData.phone;
        this.form.detail = addressData.detail;
        this.form.isDefault = addressData.isDefault;
        this.findAndSetCityIds(addressData);
      } else {
        this.isEdit = false;
        this.editAddressId = null;
        if (this.$refs["form"]) {
          this.$refs["form"].resetFields();
        }
        this.form.realName = null;
        this.form.phone = null;
        this.form.detail = null;
        this.form.province = null;
        this.form.city = null;
        this.form.district = null;
        this.city = [];
        this.district = [];
      }
    },
    findAndSetCityIds(addressData) {
      const provinceItem = this.province.find(p => p.name === addressData.province);
      if (provinceItem) {
        this.form.province = provinceItem.name;
        this.city = provinceItem.children || [];
        const cityItem = this.city.find(c => c.name === addressData.city);
        if (cityItem) {
          this.form.city = cityItem.name;
          this.form.cityId = cityItem.cityId;
          this.district = cityItem.children || [];
          const districtItem = this.district.find(d => d.name === addressData.district);
          if (districtItem) {
            this.form.district = districtItem.name;
          }
        }
      }
    },
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.isEdit) {
            this.form.addressId = this.editAddressId;
            updateUserAddress(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.$emit("addUserAddress");
              }
            });
          } else {
            addUserAddress(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.$emit("addUserAddress");
              }
            });
          }
        }
      });
    },
  }
};
</script>
<style scoped>

</style>
