<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="用户" prop="uid">
        <el-select v-model="queryParams.uid" placeholder="请选择用户" clearable filterable>
          <el-option v-for="item in userDataList" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="收货人" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入收货人"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="电话" prop="phone">
        <el-input
          v-model="queryParams.phone"
          placeholder="请输入电话"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="具体地址" prop="info">
        <el-input
          v-model="queryParams.info"
          placeholder="请输入具体地址"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="默认" prop="isDefault">
        <el-select v-model="queryParams.isDefault" placeholder="请选择默认" clearable>
          <el-option
            v-for="dict in dict.type.user_address_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:UserAddress:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:UserAddress:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:UserAddress:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:UserAddress:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="UserAddressList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="id" />
      <el-table-column label="用户" align="center" prop="uname" />
      <el-table-column label="收货人" align="center" prop="name" />
      <el-table-column label="电话" align="center" prop="phone" />
      <el-table-column label="具体地址" align="center" prop="info" />
      <el-table-column label="默认" align="center" prop="isDefault">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.user_address_status" :value="scope.row.isDefault"/>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createdAt" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createdAt, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="更新时间" align="center" prop="updatedAt" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updatedAt, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <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="['system:UserAddress:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system: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="65%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="ID" prop="id">
          <el-input v-model="form.id" placeholder="自动生成" :disabled="true" />
        </el-form-item>
        <el-form-item label="用户" prop="uid">
          <el-select v-model="form.uid" placeholder="请选择用户" clearable filterable>
            <el-option v-for="item in userDataList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="收货人" prop="name">
          <el-input v-model="form.name" 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-input
            v-model="searchAddress"
            placeholder="请输入地址"
            style="width: 200px; margin-right: 8px;"
            @keyup.enter.native="searchMapAddress"
          />
          <el-button icon="el-icon-search" @click="searchMapAddress"></el-button>
          <el-input
            v-model="latlng"
            placeholder="经纬度"
            style="width: 220px; margin-left: 8px;"
            readonly
          />
        </el-form-item>
        <div id="map" style="width: 100%; height: 250px; margin-bottom: 16px;"></div>
        <el-form-item label="具体地址" prop="info">
          <el-input v-model="form.info" placeholder="请输入具体地址" />
        </el-form-item>
        <el-form-item label="默认" prop="isDefault">
          <el-radio-group v-model="form.isDefault">
            <el-radio v-for="dict in dict.type.user_address_status" :key="dict.value" :label="parseInt(dict.value)">{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="创建时间" prop="createdAt">
          <el-date-picker clearable v-model="form.createdAt" type="date" value-format="yyyy-MM-dd" placeholder="请选择创建时间"></el-date-picker>
        </el-form-item>
        <el-form-item label="更新时间" prop="updatedAt">
          <el-date-picker clearable v-model="form.updatedAt" type="date" value-format="yyyy-MM-dd" placeholder="请选择更新时间"></el-date-picker>
        </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 { listUserAddress, getUserAddress, delUserAddress, addUserAddress, updateUserAddress,getUserDataList } from "@/api/system/UserAddress"

export default {
  name: "UserAddress",
  dicts: ['user_address_status'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      userDataList: [],
      total: 0,
      // 用户收货地址表格数据
      UserAddressList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        uid: null,
        name: null,
        phone: null,
        info: null,
        isDefault: null,
        updatedAt: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        uid: [
          { required: true, message: "用户不能为空", trigger: "blur" }
        ],
        name: [
          { required: true, message: "收货人不能为空", trigger: "blur" }
        ],
        phone: [
          { required: true, message: "电话不能为空", trigger: "blur" }
        ],
        info: [
          { required: true, message: "具体地址不能为空", trigger: "blur" }
        ],
        isDefault: [
          { required: true, message: "默认  1：是 ，0：否不能为空", trigger: "change" }
        ],
      },
      searchAddress: '',
      latlng: '',
      map: null,
      marker: null,
      geocoder: null,
      mapInited: false,
    }
  },
  created() {
    this.getList()
    this.getuserDataList()
  },
  methods: {
    /** 查询用户收货地址列表 */
    getList() {
      this.loading = true
      listUserAddress(this.queryParams).then(response => {
        this.UserAddressList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      // 关闭弹窗时销毁地图，防止下次打开异常
      if (this.map) {
        this.map.destroy();
        this.map = null;
        this.marker = null;
        this.geocoder = null;
        this.mapInited = false;
      }
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        uid: null,
        name: null,
        phone: null,
        latitude: null,
        longitude: null,
        addressName: null,
        addressInfo: null,
        info: null,
        isDefault: null,
        createdAt: null,
        updatedAt: null,
        deletedAt: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    getuserDataList(){
      getUserDataList("1").then(response => {
        this.userDataList = response.data
      })
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加用户收货地址"
      this.$nextTick(() => {
        this.searchAddress = ''
        this.latlng = ''
        this.initMap()
      })
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getUserAddress(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改用户收货地址"
        this.$nextTick(() => {
          this.searchAddress = ''
          this.latlng = this.form.longitude && this.form.latitude ? `${this.form.longitude},${this.form.latitude}` : ''
          this.initMap()
        })
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateUserAddress(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addUserAddress(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除用户收货地址编号为"' + ids + '"的数据项？').then(function() {
        return delUserAddress(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/UserAddress/export', {
        ...this.queryParams
      }, `UserAddress_${new Date().getTime()}.xlsx`)
    },
    initMap() {
      // 销毁旧地图和事件，防止重复绑定
      if (this.map) {
        this.map.destroy();
        this.map = null;
        this.marker = null;
        this.geocoder = null;
        this.mapInited = false;
      }
      this.map = new AMap.Map('map', {
        zoom: 16,
        center: [this.form.longitude || 108.94141, this.form.latitude || 34.209883],
      });
      this.geocoder = new AMap.Geocoder();
      if (this.form.longitude && this.form.latitude) {
        this.setMapMarker([this.form.longitude, this.form.latitude]);
        this.map.setCenter([this.form.longitude, this.form.latitude]);
      }
      this.map.on('click', (e) => {
        const lnglat = [e.lnglat.lng, e.lnglat.lat];
        this.setMapMarker(lnglat);
        this.form.longitude = e.lnglat.lng;
        this.form.latitude = e.lnglat.lat;
        this.latlng = `${e.lnglat.lng},${e.lnglat.lat}`;
        this.geocoder.getAddress(lnglat, (status, result) => {
          // if (status === 'complete' && result.regeocode) {
          //   this.form.info = result.regeocode.formattedAddress;
          // }
        });
      });
      this.mapInited = true;
    },
    setMapMarker(lnglat) {
      if (this.marker) {
        this.marker.setMap(null);
      }
      this.marker = new AMap.Marker({
        position: lnglat,
        map: this.map,
      });
    },
    searchMapAddress() {
      if (!this.searchAddress) {
        this.$message.warning('请输入要搜索的地址');
        return;
      }
      if (!this.mapInited || !this.geocoder) {
        this.$message.warning('地图未初始化，请稍后再试');
        return;
      }
      this.geocoder.getLocation(this.searchAddress, (status, result) => {
        if (status === 'complete' && result.geocodes.length) {
          const lnglat = result.geocodes[0].location;
          this.setMapMarker([lnglat.lng, lnglat.lat]);
          this.map.setCenter([lnglat.lng, lnglat.lat]);
          this.form.longitude = lnglat.lng;
          this.form.latitude = lnglat.lat;
          this.latlng = `${lnglat.lng},${lnglat.lat}`;
         // this.form.info = result.geocodes[0].formattedAddress;
          if ('addressName' in this.form) {
            this.form.addressName = result.geocodes[0].formattedAddress;
          }
          if ('addressInfo' in this.form) {
            this.form.addressInfo = result.geocodes[0].formattedAddress;
          }
        } else {
          this.$message.warning('未找到该地址，请输入更详细的地址');
        }
      });
    },
  }
}
</script>
