<template>
  <!-- 地址管理 -->
  <div class="address-wrapper address">
    <div class="user-com-title">收货地址</div>
    <el-form
      style="width: 60%"
      label-position="left"
      label-width="120px"
      :model="addressForm"
      :rules="rules"
      ref="addressForm"
    >
      <el-form-item label="收货人" prop="name">
        <el-input v-model="addressForm.name" placeholder="请填写收货人"></el-input>
      </el-form-item>
      <el-form-item label="手机号码" prop="mobile">
        <el-input v-model="addressForm.mobile" placeholder="请输入手机号码"></el-input>
      </el-form-item>
      <el-form-item label="所在地区" prop="district_id">
        <el-select
          style="width: 30%;margin-right: 16px"
          v-model="addressForm.province_id"
          placeholder="省/直辖市"
          @change="change($event, 1)"
        >
          <el-option
            v-for="item in provinceList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          ></el-option>
        </el-select>

        <el-select
          style="width: 30%;margin-right: 16px"
          v-model="addressForm.city_id"
          @change="change($event, 2)"
          placeholder="市/区"
        >
          <el-option v-for="item in cityList" :key="item.id" :label="item.name" :value="item.id"></el-option>
        </el-select>
        <el-select
          style="width: 30%;"
          v-model="addressForm.district_id"
          placeholder="区/县"
          @change="change($event, 3)"
        >
          <el-option
            v-for="item in districtList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="详细地址" prop="address">
        <el-input v-model="addressForm.address" placeholder="请填写详细地址，如小区、楼号、门牌号。"></el-input>
      </el-form-item>
      <el-form-item>
        <div slot="label" style="margin-top: 40px">
          <el-checkbox v-model="addressForm.is_default">设为默认收货地址</el-checkbox>
        </div>
        <div style="display: flex; justify-content: flex-end; margin-top: 40px">
          <el-button type="primary" @click="clicksave('addressForm')" size="small">保 存</el-button>
        </div>
      </el-form-item>
    </el-form>

    <div>
      <el-table
        :data="tableData"
        border
        style="width: 100%"
        :header-cell-style="{background: '#FAFAFA'}"
      >
        <el-table-column prop="name" label="收货人" align="center"></el-table-column>
        <el-table-column prop="mobile" label="电话" align="center"></el-table-column>
        <el-table-column prop="full_address" label="所在地区" show-overflow-tooltip align="center"></el-table-column>
        <el-table-column prop="address" label="详情地址" show-overflow-tooltip align="center"></el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <div class="cz">
              <span @click="edit(scope.row)">编辑</span>
              <span @click="bingDelete(scope.row)">删除</span>
              <span v-if="(scope.row.is_default)" style="color:#000">默认</span>
              <span @click="bindDefault(scope.row)" v-if="!(scope.row.is_default)">设为默认</span>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <el-dialog
      title="修改地址"
      :visible.sync="isEdit"
      width="40%"
      v-if="isEdit"
      :show-close="false"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form
        style="width: 100%"
        label-position="left"
        label-width="120px"
        :model="editForm"
        :rules="rules"
        ref="editForm"
      >
        <el-form-item label="收货人" prop="name">
          <el-input v-model="editForm.name" placeholder="请填写收货人"></el-input>
        </el-form-item>
        <el-form-item label="手机号码">
          <el-input v-model="editForm.mobile" placeholder="请输入手机号码" prop="mobile"></el-input>
        </el-form-item>
        <el-form-item label="所在地区" prop="district_id">
          <el-select
            style="width: 30%;margin-right: 19px"
            v-model="editForm.province_id"
            placeholder="省/直辖市"
            @change="change($event, 1)"
          >
            <el-option
              v-for="item in provinceList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>

          <el-select
            style="width: 30%;margin-right: 19px"
            v-model="editForm.city_id"
            @change="change($event, 2)"
            placeholder="市/区"
          >
            <el-option v-for="item in cityList" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
          <el-select
            style="width: 30%;"
            v-model="editForm.district_id"
            placeholder="区/县"
            @change="change($event, 3)"
          >
            <el-option
              v-for="item in districtList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="详细地址" prop="address">
          <el-input v-model="editForm.address" placeholder="请填写详细地址，如小区、楼号、门牌号。"></el-input>
        </el-form-item>
        <el-form-item>
          <div style="display: flex; justify-content: flex-end; margin-bottom: 40px">
            <el-button @click="isEdit=false" size="small">取 消</el-button>
            <el-button type="primary" @click="clicksave('editForm')" size="small">保 存</el-button>
          </div>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import validator from "@/mixins/validator";
import areaList from "@/mixins/areaList";
export default {
  name: "addressList",
  auth: "guest",
  mixins: [areaList, validator],
  data() {
    return {
      userInfo: JSON.parse(localStorage.getItem("userInfo")),
      addressForm: {
        name: "",
        mobile: "",

        province_id: "", //省份id
        city_id: "", //城市id
        district_id: "", //区县id

        province: "",
        city: "",
        district: "",

        community_id: 0,
        address: "",
        is_default: 0,

        full_address: "",
        telephone: "", //手机
        community_id: 0, //社区id
        longitude: "", //经度
        latitude: "" //纬度
      },
      editForm: {},

      isEdit: false,
      tableData: []
    };
  },
  async asyncData({ app }) {
    let [provinceList] = await Promise.all([
      // 省市区
      app.$axios.post("/address/lists")
    ]);
    return {
      provinceList: provinceList.data
    };
  },
  fetch({ store }) {
    store.commit("isHeader", true);
    store.commit("isFooter", true);
  },
  head() {
    return {
      title: "收货地址-" + this.$store.state.titleCon
    };
  },
  created() {},
  mounted() {
    this.getList();
  },
 
  methods: {
    getList() {
      let obj = {
        member_id: this.userInfo.member_id
      };
      this.$axios
        .post(`/memberaddress/page`, obj)
        .then(res => {
          console.log(res.data.list);
          this.tableData = res.data.list;
        })
        .catch(err => {
          this.$message.error("err");
        });
    },
    // 获取市区
    change(pid, i) {
      // 省名
      if (i == 1) {
        this.provinceList.forEach(item => {
          if (pid == item.id) {
            this.addressForm.province = item.name;
            this.editForm.province = item.name;
          }
        });
      }
      // 市名
      else if (i == 2) {
        this.cityList.forEach(item => {
          if (pid == item.id) {
            this.addressForm.city = item.name;
            this.editForm.city = item.name;
          }
        });
      }
      // 区名
      else if (i == 3) {
        this.districtList.forEach(item => {
          if (pid == item.id) {
            this.addressForm.district = item.name;
            this.editForm.district = item.name;
          }
        });
      }

      this.$axios
        .post("/address/lists", {
          pid
        })
        .then(res => {
          if (i == 1) {
            this.cityList = res.data;
            this.addressForm.city_id = "";
            this.addressForm.district_id = "";
          }
          if (i == 2) {
            this.districtList = res.data;
            this.addressForm.district_id = "";
          }
        })
        .catch(err => {
          this.$message.error(err);
        });
    },
    //
    clicksave(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          // 新增
          if (!this.isEdit) {
            let obj = { ...this.addressForm };
            obj.full_address =
              obj.province + "-" + obj.city + "-" + obj.district;
            this.$axios
              .post("/memberaddress/add", obj)
              .then(res => {
                this.$message.success(res.message);
                this.addressForm = {
                  name: "",
                  mobile: "",
                  province_id: "", //省份id
                  city_id: "", //城市id
                  district_id: "", //区县id
                  province: "",
                  city: "",
                  district: "",
                  community_id: 0,
                  address: "",
                  is_default: 0,
                  full_address: "",
                  telephone: "", //手机
                  community_id: 0, //社区id
                  longitude: "", //经度
                  latitude: "" //纬度
                };

                this.getList();
              })
              .catch(err => {
                this.$message.error(err);
              });

            this.isEdit = false;
          }
          // 修改
          else {
            let obj = { ...this.editForm };
            obj.full_address =
              obj.province + "-" + obj.city + "-" + obj.district;
            this.$axios
              .post("/memberaddress/edit", obj)
              .then(res => {
                this.$message.success(res.message);
                this.editForm = {};
                this.getList();
              })
              .catch(err => {
                this.$message.error(err);
              });
            console.log(`修改`);
            this.isEdit = false;
          }
        }
      });
    },
    // 设为默认
    bindDefault(item) {
      this.$axios
        .post("/memberaddress/setdefault", {
          id: item.id
        })
        .then(res => {
          this.$message.success("设置成功");
          this.getList();
        })
        .catch(err => {
          this.$message.error(err);
        });
    },
    // 删除
    bingDelete(item, index) {
      this.$confirm("确定删除该地址吗", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(res => {
        this.$axios
          .post("/memberaddress/delete", {
            id: item.id
          })
          .then(data => {
            this.getList();
            this.$message.success("删除成功");
          });
      });
    },
    // 编辑
    edit(item) {
      console.log(item);
      this.editForm = item;
      this.isEdit = true;
      this.getAreaData(item.province_id, 1);
      this.getAreaData(item.city_id, 2);
    }
  }
};
</script>

<style lang="scss" scoped>
::v-deep {
  .el-input__inner {
    height: 32px;
    line-height: 32px;
  }
  .el-form-item__content {
    line-height: 32px;
  }
  .el-form-item__label {
    line-height: 32px;
  }
  .el-form-item {
    margin-bottom: 20px;
  }
  .el-form-item__label {
    font-size: 13px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: #666666;
  }
  .el-button--primary {
    background-color: var(--themeColor);
    border-color: var(--themeColor);
  }
}
.cz {
  font-size: 14px;
  font-family: PingFangSC-Regular, PingFang SC;
  font-weight: 400;
  color: var(--themeColor);
  cursor: pointer;
}
.address {
  padding: 0 30px;
  .user-com-title {
    margin-bottom: 20px;
  }
  .code {
    width: 100px;
    height: 32px;
    line-height: 32px;
    text-align: center;

    border-radius: 4px;
    border: 1px solid var(--themeColor);
    font-size: 12px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: var(--themeColor);
    margin-left: 10px;
    cursor: pointer;
  }
}
</style>
