<template>
  <div class="userCenterMyAddress">
    <div class="title">
      {{ $t("common.myAddress") }}
      {{
        $i18n.locale == "zh"
          ? `（您已创建 ${page.total} 个收货地址，最多可创建 25 个）`
          : `（You have created ${page.total} shipping addresses, up to 25）`
      }}
    </div>
    <div class="table">
      <div style="text-align: right">
        <el-button
          type="primary"
          style="margin: 20px 0 8px"
          @click="addAddress"
        >
          <i class="el-icon-plus"></i>
          {{ $i18n.locale == "zh" ? "新建地址" : "Create New Address" }}
        </el-button>
      </div>
      <div>
        <el-table
          :data="umsUserCommodityAddress"
          v-loading="loading"
          style="width: 100%"
          height="588"
          :header-cell-style="{ backgroundColor: '#f8f8f8' }"
        >
          <el-table-column
            prop="consignee"
            align="center"
            :label="$i18n.locale === 'zh' ? '收货人' : 'Consignee'"
            width="150"
          >
          </el-table-column>
          <el-table-column
            v-if="$i18n.locale == 'zh'"
            align="center"
            :label="$i18n.locale === 'zh' ? '所在地区' : 'Region'"
            width="150"
          >
            <template slot-scope="scope">
              {{ scope.row.province }}{{ scope.row.city }}{{ scope.row.area }}
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            :label="$i18n.locale === 'zh' ? '详细地址' : 'Address'"
            min-width="160"
          >
            <template slot-scope="scope">
              {{ scope.row.address }}
            </template>
          </el-table-column>
          <el-table-column
            prop="postalCode"
            align="center"
            :label="$i18n.locale === 'zh' ? '邮编' : 'Postcode'"
            width="150"
          >
          </el-table-column>
          <el-table-column
            prop="mobile"
            align="center"
            :label="$i18n.locale === 'zh' ? '联系方式' : 'Contact information'"
            width="160"
          >
          </el-table-column>
          <el-table-column
            align="center"
            :label="$i18n.locale === 'zh' ? '操作' : 'Operate'"
            width="160"
          >
            <template slot-scope="scope">
              <el-button
                type="text"
                size="small"
                @click="alterAddress(scope.row)"
              >
                {{ $i18n.locale === "zh" ? "编辑" : "Edit" }}
              </el-button>
              <el-button
                type="text"
                size="small"
                @click="deleteAddress(scope.row.id)"
              >
                {{ $i18n.locale === "zh" ? "删除" : "Delete" }}
              </el-button>
              <el-button
                disabled
                type="text"
                size="small"
                v-if="scope.row.status != '1'"
                @click="alterAddressStatus(scope.row)"
              >
                {{ $i18n.locale === "zh" ? "设为默认地址" : "Set Default Address" }}
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          background
          @size-change="
            (val) => {
              page.pageSize = val;
            }
          "
          @current-change="
            (val) => {
              page.pageNo = val;
            }
          "
          layout="prev, pager, next"
          :total="page.total"
          :current-page="page.pageNo"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="page.pageSize"
          style="text-align: center; margin-top: 20px"
        >
        </el-pagination>
      </div>
    </div>
    <el-dialog
      destroy-on-close
      :modal="false"
      custom-class="userCenterMyAddressDialog"
      :visible.sync="booleanFlag.addressFlag"
      width="700px"
      @close="userCenterMyAddressDialogClose"
    >
      <span slot="title">
        <span v-if="addressDialogConfig.type == '新建地址'">
          {{ $i18n.locale == "zh" ? "新建地址" : "New address" }}
        </span>
        <span v-if="addressDialogConfig.type == '修改地址'">
          {{ $i18n.locale == "zh" ? "修改地址" : "Modification address" }}
        </span>
      </span>
      <div class="content">
        <el-form
          :rules="this.isZh ? rules : rulesEn"
          ref="addressForm"
          :model="addressForm"
          label-width="150px"
        >
          <el-form-item
            :label="$i18n.locale == 'zh' ? '收货人' : 'Consignee'"
            prop="consignee"
          >
            <el-input
              maxlength="30"
              v-model="addressForm.consignee"
              :placeholder="
                $i18n.locale == 'zh'
                  ? '长度不超过30个字符'
                  : '30 characters or less in length'
              "
            ></el-input>
          </el-form-item>
          <el-form-item
            :label="$i18n.locale == 'zh' ? '电话号码' : 'Mobile'"
            prop="mobile"
          >
            <el-input
              v-model="addressForm.mobile"
              :placeholder="
                $i18n.locale == 'zh'
                  ? '电话号码、手机号码必须填一项'
                  : 'Phone number, mobile phone number must fill in one item'
              "
            ></el-input>
          </el-form-item>
          <el-form-item
            v-if="$i18n.locale == 'zh'"
            :label="$i18n.locale == 'zh' ? '地址信息' : 'Division'"
            required
            prop="division"
          >
            <el-cascader
              v-model="addressForm.division"
              :options="sysAreaList"
              :props="{ value: 'name', label: 'name', children: 'child' }"
              placeholder="请选择省/市/区/街道"
            >
            </el-cascader>
          </el-form-item>
          <el-form-item
            :label="$i18n.locale == 'zh' ? '详细地址' : 'Detail'"
            prop="address"
          >
            <el-input
              v-model="addressForm.address"
              :placeholder="
                $i18n.locale == 'zh' ? '请输入详细地址' : 'Please enter address'
              "
            ></el-input>
          </el-form-item>
          <el-form-item :label="$i18n.locale == 'zh' ? '邮政编码' : 'Postcode'">
            <el-input v-model="addressForm.postal_code"></el-input>
          </el-form-item>
          <el-form-item label=" ">
            <el-checkbox
              v-model="addressForm.status"
              true-label="1"
              false-label="0"
              >{{
                $i18n.locale == "zh" ? "设为默认" : "Set as Default"
              }}</el-checkbox
            >
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="saveAddress('addressForm')"
              >{{
                $i18n.locale == "zh" ? "保存" : "Save"
              }}</el-button
            >
          </el-form-item>
        </el-form>
      </div>
    </el-dialog>
  </div>
</template>


<script>
import {
  addUmsUserCommodityAddresss,
  deleteUmsUserCommodityAddresss,
  getSysAreaList,
  getUmsUserCommodityAddresss,
} from "@/api/user";
import { getToken } from "@/api/token";

export default {
  name: "userCenterMyAddress",
  data() {
    return {
      isZh: true,
      booleanFlag: {
        addressFlag: false,
      },
      user: {
        umsUser: {},
      },
      loading: true,
      page: {
        pageNo: 1,
        pageSize: 10,
        total: 0,
      },
      sysAreaList: [],
      umsUserCommodityAddress: [],
      addressDialogConfig: {
        type: "新建地址",
      },
      addressForm: {
        consignee: "",
        mobile: "",
        division: [],
        address: "",
        postal_code: "",
        status: "0",
      },
      rules: {
        consignee: [
          {
            required: true,
            message: "请输入收货人",
            trigger: "blur",
          },
        ],
        mobile: [
          {
            required: true,
            message: "请输入电话号码或手机号码",
            trigger: "blur",
          },
        ],
        division: [
          {
            required: true,
            message: "请选择地址信息",
            trigger: "change",
          },
        ],
        address: [
          {
            required: true,
            message: "请输入详细地址信息",
            trigger: "blur",
          },
        ],
      },
      rulesEn: {
        consignee: [
          {
            required: true,
            message: "Please enter the consignee",
            trigger: "blur",
          },
        ],
        mobile: [
          {
            required: true,
            message: "Please enter a phone number or mobile number",
            trigger: "blur",
          },
        ],
        address: [
          {
            required: true,
            message: "Please enter detailed address information",
            trigger: "blur",
          },
        ],
      },
    };
  },
  watch: {
    page: {
      handler: function () {
        this.loading = true;
        this.getUmsUserCommodityAddresss();
      },
      deep: true,
    },
    "$i18n.locale": {
      handler: function () {
        if (this.$i18n.locale == "zh") {
          this.isZh = true;
        } else {
          this.isZh = false;
        }
      },
      deep: true,
    },
  },
  mounted() {
    let test =  JSON.parse(this.$Cookies.get('userInfo'));
    console.log(test)
    let language = window.localStorage.getItem("locale");
    if (language == "zh") {
      this.isZh = true;
    } else {
      this.isZh = false;
    }
    this.getSysAreaList();
    this.init();
  },
  methods: {
    init() {
      this.user = JSON.parse(window.localStorage.getItem("user"));
      if (this.user.umsUser.userPic == undefined) {
        this.user.umsUser.userPic = "";
      }
      this.getUmsUserCommodityAddresss();
    },
    //  获取省市区
    getSysAreaList() {
      function clearLeaf(data) {
        data.forEach((item, index) => {
          if (item.child.length != 0) {
            clearLeaf(item.child);
          } else {
            item.child = undefined;
          }
        });
      }

      getSysAreaList().then((res) => {
        if (res) {
          let data = res.data;
          clearLeaf(data);
          this.sysAreaList = data;
          console.log(this.sysAreaList)
        }
      });
    },
    //  获取地址列表
    getUmsUserCommodityAddresss() {
      let param = {
        pageSize: this.page.pageSize,
        pageNo: this.page.pageNo,
        // userId: this.user.userId,
      };
      getUmsUserCommodityAddresss(param)
        .then((res) => {
          if (res) {
            console.log(res);
            this.umsUserCommodityAddress = res.data.umsUserCommodityAddresss;
            this.page.total = Number(res.data.page.totalCount);
          }
        })
        .then(() => {
          this.loading = false;
        })
        .catch(() => {
          this.loading = false;
        });
    },
    addAddress() {
      this.addressDialogConfig.type = "新建地址";
      this.booleanFlag.addressFlag = true;
    },
    saveAddress(addressForm) {
      let params = {
        id: this.addressForm.id,
        // userId: this.user.userId,
        consignee: this.addressForm.consignee,
        mobile: this.addressForm.mobile,
        province: this.addressForm.division[0],
        city: this.addressForm.division[1],
        area: this.addressForm.division[2],
        address: this.addressForm.address,
        postalCode: this.addressForm.postal_code,
        status: this.addressForm.status,
      };
      this.$refs[addressForm].validate((valid) => {
        if (valid) {
          this.booleanFlag.addressFlag = false;
          getToken().then((res) => {
            addUmsUserCommodityAddresss(params, res.data).then((res) => {
              this.init();
            });
          });
        } else {
          return false;
        }
      });
    },
    //  编辑
    alterAddress(data) {
      this.addressForm = {
        consignee: data.consignee,
        mobile: data.mobile,
        division: [data.province, data.city, data.area],
        address: data.address,
        postal_code: data.postalCode,
        status: data.status,
        id: data.id,
      };
      console.log(this.addressForm);
      this.addressDialogConfig.type = "修改地址";
      this.booleanFlag.addressFlag = true;
    },
    // 设为默认地址
    alterAddressStatus(data) {
      let params = {
        // user_id: this.user.userId,
        consignee: data.consignee,
        mobile: data.mobile,
        province: data.province,
        city: data.city,
        area: data.area,
        address: data.address,
        postal_code: data.postalCode,
        status: "1",
        id: data.id,
      };
      getToken().then((res) => {
        addUmsUserCommodityAddresss(params, res.data).then((res) => {
          this.init();
        });
      });
    },
    deleteAddress(id) {
      getToken().then((res) => {
        // res.data 为token
        deleteUmsUserCommodityAddresss(id, res.data)
          .then((res) => {
            this.init();
          })
          .catch((error) => {
            console.log(error);
          });
      });
    },
    userCenterMyAddressDialogClose() {
      this.addressForm = this.$options.data.call(this).addressForm;
    },
  },
};
</script>

<style scoped lang="less">
.userCenterMyAddress {
  height: 700px;

  overflow:hidden .title {
    height: 60px;
    line-height: 60px;
    padding-top: 30px;
    margin-left: 30px;
    margin-right: 30px;
    border-bottom: 1px solid rgba(228, 228, 228, 1);
  }

  > .table {
    padding: 0 5px;
  }

  /deep/ .userCenterMyAddressDialog {
    margin-top: 300px;
  }
}
</style>
