<template>
  <div >
    <el-row :gutter="10" class="mb8" style="float: right; top: -30px;">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['his:userAddress:add']"
        >新增</el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" border="" :data="userAddressList" @selection-change="handleSelectionChange" style="top: -30px;">
      <el-table-column label="收货人姓名" align="center" prop="realName" />
      <el-table-column label="收货人电话" align="center" prop="phone" />
      <el-table-column label="收货人所在省" align="center" prop="province" />
      <el-table-column label="收货人所在市" align="center" prop="city" />
      <el-table-column label="收货人所在区" align="center" prop="district" />
      <el-table-column label="收货人详细地址" align="center" prop="detail" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['his:userAddress:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['his:userAddress:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改用户地址对话框 -->
   <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
         <el-form ref="form" :model="form" :rules="rules" label-width="100px">
         <el-form-item label="智能识别" prop="address">
           <el-input v-model="address" placeholder="输入需要识别的地址" >  <el-button slot="append" icon="el-icon-search" @click="sAddress"></el-button></el-input>
         </el-form-item>
           <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="省市区" >
             <el-cascader
             ref="citySelect"
             v-model="cityIds"
             :options="citys"
             @change="handleCityChange">
             </el-cascader>
           </el-form-item>
           <el-form-item label="详细地址" prop="detail">
             <el-input v-model="form.detail" placeholder="请输入收货人详细地址" />
           </el-form-item>
          <el-form-item label="是否默认地址" prop="isDefault">
                        <el-radio-group v-model="form.isDefault">
                                 <el-radio :label="item.dictValue" v-for="item in orOptions" >{{item.dictLabel}}</el-radio>
                        </el-radio-group>
          </el-form-item>
         </el-form>
         <div slot="footer" class="dialog-footer">
           <el-button type="primary" @click="submitForm">确 定</el-button>
           <el-button @click="cancel">取 消</el-button>
         </div>
       </el-dialog>
  </div>
</template>

<script>
import { getAddress,listUserAddress, getUserAddress, delUserAddress, addUserAddress, updateUserAddress, exportUserAddress } from "@/api/store/userAddress";
import {getCitys} from "@/api/store/city";
export default {
  name: "UserAddress",
  data() {
    return {
      orOptions:[],
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户地址表格数据
      userAddressList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      cityIds:null,
      address:null,
      citys:[],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userId: null,
        realName: null,
        phone: null,
        province: null,
        city: null,
        district: null,
        cityIds: null,
        detail: null,
        postCode: null,
        longitude: null,
        latitude: null,
        isDefault: null,
        isDel: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        userId: [
          { required: true, message: "用户id不能为空", trigger: "blur" }
        ],
        realName: [
          { required: true, message: "收货人姓名不能为空", trigger: "blur" }
        ],
        phone: [
          { required: true, message: "收货人电话不能为空", trigger: "blur" },
          {
                      pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
                      message: "请输入正确的手机号码",
                      trigger: "blur"
                    }
        ],
        province: [
          { required: true, message: "收货人所在省不能为空", trigger: "blur" }
        ],
        city: [
          { required: true, message: "收货人所在市不能为空", trigger: "blur" }
        ],
        district: [
          { required: true, message: "收货人所在区不能为空", trigger: "blur" }
        ],
        detail: [
          { required: true, message: "收货人详细地址不能为空", trigger: "blur" }
        ],
        isDefault: [
          { required: true, message: "是否默认不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getCitys();
    this.getDicts("sys_company_or").then(response => {
      this.orOptions = response.data;
    });
  },
  methods: {

    /** 查询用户地址列表 */
    getList() {
      this.loading = true;
      listUserAddress(this.queryParams).then(response => {
        this.userAddressList = response.rows;
        this.total = response.total;
        this.loading = false;

      });
    },
    getAddList(id) {
      this.queryParams.userId=id;
      this.loading = true;
      listUserAddress(this.queryParams).then(response => {
        this.userAddressList = response.rows;
        this.total = response.total;
        this.loading = false;

      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        addressId: null,
        userId: null,
        realName: null,
        phone: null,
        province: null,
        city: null,
        district: null,
        cityIds: null,
        detail: null,
        postCode: null,
        longitude: null,
        latitude: null,
        isDefault: null,
        isDel: null,
        createTime: null,
        updateTime: null
      };
      this.address=null;
      this.cityIds=[];
      this.resetForm("form");
    },
    getCitys(){
        getCitys().then(res => {
          this.citys=res.data;
        })
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList(this.queryParams.userId);
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.addressId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    handleCityChange(value) {
      var nodes=this.$refs.citySelect.getCheckedNodes();
      this.cityIds=value.toString();
      this.form.province=nodes[0].pathLabels[0];
      this.form.city=nodes[0].pathLabels[1];
      this.form.district=nodes[0].pathLabels[2];
    },

    sAddress(){
      getAddress(this.address).then(response => {
        var addressJson = response.data;
        this.msgSuccess(addressJson.reason);
        this.form.province=addressJson.data.provinceName;
        this.form.city=addressJson.data.cityName;
        this.form.district=addressJson.data.expAreaName;
        this.form.detail=addressJson.data.streetName+addressJson.data.address;
        this.form.realName=addressJson.data.name;
        this.form.phone=addressJson.data.mobile;
        var province= this.citys.find(function(o) {
           return o.label ==addressJson.data.provinceName ;
         });
         var city= province.children.find(function(o) {
            return o.label == addressJson.data.cityName;
          });
        var district= city.children.find(function(o) {
             return o.label == addressJson.data.expAreaName;
           });
        this.cityIds=[province.value,city.value,district.value]
      });
    },


    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加用户地址";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const addressId = row.addressId || this.ids
      getUserAddress(addressId).then(response => {
        this.form = response.data;
        var province= this.citys.find(function(o) {
           return o.label ==response.data.province ;
         });
         var city= province.children.find(function(o) {
            return o.label == response.data.city;
          });
          var district= city.children.find(function(o) {
             return o.label == response.data.district;
           });
        this.cityIds=[province.value,city.value,district.value]
        this.open = true;
        this.title = "修改用户地址";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if(this.form.city==null||this.form.province==null||this.form.district==null){
           return this.msgSuccess("省市区不能为空");
          }
          if (this.form.addressId != null) {
            updateUserAddress(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList(this.queryParams.userId);
            });
          } else {
            this.form.userId=this.queryParams.userId
            addUserAddress(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList(this.queryParams.userId);
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const addressIds = row.addressId || this.ids;
      this.$confirm('是否确认删除用户地址编号为"' + addressIds + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delUserAddress(addressIds);
        }).then(() => {
          this.getList(this.queryParams.userId);
          this.msgSuccess("删除成功");
        }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有用户地址数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.exportLoading = true;
          return exportUserAddress(queryParams);
        }).then(response => {
          this.download(response.msg);
          this.exportLoading = false;
        }).catch(() => {});
    }
  }
};
</script>
