<template>
  <div class="address-management">
    <div class="header">
      <div class="num">已保存<span>{{addressList.length}}</span>/100条,最多还可以添加<span>{{100-addressList.length}}</span>条</div>
      <el-button class="btn" @click="showAddress(false)" size="small" type="primary" plain>添加</el-button>
    </div>
    <el-table :data="addressList" stripe style="width: 100%">
      <el-table-column prop="contact" label="姓名">
      </el-table-column>
      <el-table-column prop="phone" label="电话">
      </el-table-column>
      <el-table-column prop="address" label="地址">
      </el-table-column>
      <el-table-column label="操作" width="100">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="showAddress(true,scope.row)">编辑</el-button>
          <el-button @click="deleteAddress(scope.row)" type="text" size="small">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- //新增编辑地址 -->
    <el-dialog :title="isEdit ? '编辑地址': '新增地址'" :visible.sync="centerDialogVisible" width="600px" center append-to-body>
      <el-form ref="form" :model="form" label-width="100px" label-position="left" size="small">
        <el-form-item label="位置" required>
          <el-input v-model="form.address" placeholder="请选择位置！" disabled>
            <img @click="showMap" slot="append" class="map" src="../../static/image/icon_map.png" />
          </el-input>
        </el-form-item>
        <el-form-item label="门牌号">
          <el-input v-model="form.street" placeholder="请填写楼层、单元、门牌号！"></el-input>
        </el-form-item>
        <el-form-item label="联系人姓名" required>
          <el-input v-model="form.contact" placeholder="请填写联系人姓名！"></el-input>
        </el-form-item>
        <el-form-item label="联系人电话" required>
          <el-input v-model="form.phone" placeholder="请填写联系人电话！"></el-input>
        </el-form-item>
        <el-form-item label="设为默认地址">
          <el-switch v-model="form.isDefault" :active-value="1" :inactive-value="0" active-color="#FC7200" inactive-color="#999"></el-switch>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="cancel">取 消</el-button>
        <el-button size="small" type="primary" @click="addAddress">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 通过地图选择地理位置 -->
    <order-map @getAddressDetail="getAddressDetail" ref="orderMap"></order-map>
  </div>
</template>

<script>
import orderMap from "./orderComponents/orderAMap.vue";
import {
  getAddressList,
  deleteAddress,
  addAddress,
  updateAddress,
  getAddressDetail,
  defaultAddress,
} from "../api/setting.js";
export default {
  name: "addressManagement",
  data() {
    return {
      addressList: [],
      centerDialogVisible: false,
      isEdit: false,
      form: {
        id: "",
        address: "",
        cityCode: "",
        cityName: "",
        contact: "",
        districtName: "",
        isDefault: 0,
        lat: "",
        lng: "",
        phone: "",
        provinceName: "",
        street: "",
      },
    };
  },
  components: {
    orderMap,
  },
  // 监听属性 类似于data概念
  computed: {},
  // 监控data中的数据变化
  watch: {},
  // 生命周期 - 创建完成（可以访问当前this实例）
  created() {
    this.getAddressList();
  },
  mounted() {},
  // 方法集合
  methods: {
    cancel() {
      this.centerDialogVisible = false;
      this.getAddressList();
    },
    changeDefault() {
      defaultAddress({ addressId: this.form.id }).then((res) => {
        if (res.code === 200) {
          this.getAddressList();
        } else {
          this.$message({
            type: "error",
            message: res.msg,
          });
        }
      });
    },
    addAddress() {
      if (!this.form.address) {
        return this.$message({
          type: "error",
          message: "请选择地址的位置！",
        });
      }
      if (!this.form.contact.trim()) {
        return this.$message({
          type: "error",
          message: "请输入联系人姓名！",
        });
      }
      this.form.phone = this.form.phone.replace(/\s/g, "");
      if (!this.form.phone.trim()) {
        return this.$message({
          type: "error",
          message: "请输入联系人电话！",
        });
      }
      let reg2 = new RegExp(/^1[3456789]\d{9}$/);
      if (!reg2.test(this.form.phone)) {
        return this.$message({
          type: "error",
          message: "联系人电话格式不正确!",
        });
      }
      if (this.isEdit) {
        updateAddress(this.form).then((res) => {
          if (res.code === 200) {
            this.response();
          } else {
            this.$message({
              type: "success",
              message: res.msg,
            });
          }
        });
      } else {
        addAddress(this.form).then((res) => {
          if (res.code === 200) {
            this.response();
          } else {
            this.$message({
              type: "success",
              message: res.msg,
            });
          }
        });
      }
    },
    response() {
      this.$message({
        type: "success",
        message: `${this.isEdit ? "编辑" : "新增"}地址成功！`,
      });
      this.centerDialogVisible = false;
      this.getAddressList();
    },
    deleteAddress(row) {
      this.$confirm("此操作将删除该地址, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        center: true,
        type: "warning",
      }).then(() => {
        deleteAddress({ addressId: row.id }).then((res) => {
          if (res.code === 200) {
            this.$message({
              type: "success",
              message: "删除成功!",
            });
            this.getAddressList();
          } else {
            this.$message({
              type: "error",
              message: res.msg,
            });
          }
        });
      });
    },
    showMap() {
      this.$refs.orderMap.chooseLocation();
    },
    getAddressDetail(v, lng, lat) {
      this.form.address = v.address;
      this.form.provinceName = v.province;
      this.form.cityName = v.city;
      this.form.cityCode = v.citycode;
      this.form.districtName = v.district;
      this.form.lng = lng;
      this.form.lat = lat;
    },
    showAddress(flag, row) {
      this.isEdit = flag;
      if (flag) {
        this.form = row;
      } else {
        this.form = {
          id: "",
          address: "",
          cityCode: "",
          cityName: "",
          contact: "",
          districtName: "",
          isDefault: 0,
          lat: "",
          lng: "",
          phone: "",
          provinceName: "",
          street: "",
        };
      }
      this.centerDialogVisible = true;
    },
    getAddressList() {
      getAddressList().then((res) => {
        if (res.code === 200) {
          this.addressList = res.data.personal;
        } else {
          this.$message({
            type: "error",
            message: res.msg,
          });
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped  type="text/css">
.btn {
  background: #fc7200;
  color: #fff;
  border: #fc7200;
}
/deep/ .el-button--text {
  color: #fc7200;
}
.map {
  width: 20px;
  height: 20px;
  cursor: pointer;
}
.address-management {
  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 10px;
    .num {
      font-size: 14px;
      span {
        color: #fc7200;
      }
    }
  }
}
</style>