<template>
  <div>
    <el-dialog :title="state.form.id ? '编辑店铺' : '添加店铺'" v-model="state.dialogVisible" @close="reset">
      <div style="height: 50vh; overflow-y: auto">
        <el-form ref="refForm" :model="state.form" :rules="state.rules" label-width="120px" label-position="left">
          <el-form-item label="店铺名称" prop="shopName">
            <el-input v-model="state.form.shopName" placeholder="请输入门店名称"></el-input>
          </el-form-item>
          <el-form-item label="店铺类型">
            <el-radio-group v-model="state.form.shopType" :disabled="state.isEdit || state.type == 'addBranch'">
              <el-radio-button value="only">单店</el-radio-button>
              <el-radio-button value="chain">连锁店</el-radio-button>
              <el-radio-button value="join">加盟店</el-radio-button>
            </el-radio-group>
            <div class="tips">
              <el-alert title="请谨慎修改" type="warning" size="7" effect="dark" show-icon :closable="false" />
            </div>
          </el-form-item>
          <el-form-item label="是否为主店" prop="isHeadShop" v-if="state.form.shopType != 'only'">
            <el-radio-group v-model="state.form.isHeadShop" @change="state.form.mainId = ''"
              :disabled="state.isEdit || state.type == 'addBranch'">
              <el-radio :value="1">是</el-radio>
              <el-radio :value="0">否</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="选择主店" prop="mainId" v-if="state.form.isHeadShop == '0' && state.form.shopType != 'only'">
            <!-- <el-form-item label="主店账号" prop="mainId" v-if="state.form.shopType != 'only'"> -->
            <el-select v-model="state.form.mainId" placeholder="请选择主店铺" filterable reserve-keyword
              :remote-method="getTableData" :loading="state.shopListLoading"
              :disabled="state.isEdit || state.type == 'addBranch'">
              <el-option v-for="item in state.shopList" :label="`${item.shopName}`" :value="item.id"
                :key="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="连锁店扩展店名">
            <el-input v-model="state.form.chainName" placeholder="请输入连锁店扩展店名"></el-input>
          </el-form-item>
          <el-form-item label="门店logo" prop="logo">
            <SingleImageUpload v-model="state.form.logo" />
          </el-form-item>
          <el-form-item label="门店照片">
            <SingleImageUpload v-model="state.form.frontImg" />
          </el-form-item>
          <el-form-item label="经营模式">
            <el-radio-group v-model="state.form.registerType">
              <el-radio-button value="before">先付费</el-radio-button>
              <el-radio-button value="after">后付费</el-radio-button>
            </el-radio-group>
            <div class="tips">
              <el-alert title="请谨慎修改" type="warning" size="7" effect="dark" show-icon :closable="false" />
            </div>
          </el-form-item>
          <el-form-item label="管理方式" v-if="state.form.shopType != 'only'">
            <el-radio-group v-model="state.form.tubeType">
              <el-radio-button :value="0">不可直接管理</el-radio-button>
              <el-radio-button :value="1">直接管理</el-radio-button>
            </el-radio-group>
            <div class="tips">
              <el-alert title="请谨慎修改" type="warning" size="7" effect="dark" show-icon :closable="false" />
            </div>
          </el-form-item>
          <el-form-item label="商户版本">
            <el-radio-group v-model="state.form.profiles">
              <el-radio-button value="probation">试用</el-radio-button>
              <el-radio-button value="release">正式</el-radio-button>
            </el-radio-group>
            <div class="tips">
              <el-alert title="请谨慎修改" type="warning" size="7" effect="dark" show-icon :closable="false" />
            </div>
          </el-form-item>
          <el-form-item label="激活时长" prop="activateDuration">
            <activeDate v-model="state.form.activateDuration" v-model:activeCost="state.form.activateAmount" />
            <!-- <el-input v-model="state.form.activateDuration" placeholder="请输入激活码"></el-input>
            <div class="tips">注：输入有效激活码表示添加的同时直接激活该店铺。</div> -->
          </el-form-item>
          <el-form-item label="登录账号" prop="accountName">
            <el-input v-model="state.form.accountName" placeholder="请输入登录账号"></el-input>
          </el-form-item>
          <el-form-item label="登录密码" prop="accountPwd" v-if="!state.form.id">
            <el-input type="password" show-password v-model="state.form.accountPwd" placeholder="请输入登录密码"></el-input>
          </el-form-item>
          <el-form-item label="联系电话" prop="phone">
            <el-input v-model="state.form.phone" placeholder="请输入联系电话"></el-input>
          </el-form-item>
          <el-form-item label="设备数量">
            <el-input-number v-model="state.form.supportDeviceNumber" controls-position="right" :min="1" :step="1"
              step-strictly></el-input-number>
          </el-form-item>
          <!-- <el-form-item label="外卖起送金额">
                    <el-input-number v-model="form.takeaway_money" placeholder="0.00" controls-position="right"
                        :min="0"></el-input-number>
                </el-form-item> -->
          <el-form-item label="店铺地址" prop="districts">
            <AddressSelect v-model:prov="state.form.provinces" v-model:city="state.form.cities"
              v-model:area="state.form.districts"></AddressSelect>
          </el-form-item>

          <div>
            <el-row :gutter="20">
              <el-col :span="6">
                <el-form-item label="经度" prop="lng">
                  <el-input v-model="state.form.lng" placeholder="经度"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="4">
                <el-form-item label="纬度" prop="lat" label-width="auto">
                  <el-input v-model="state.form.lat" placeholder="纬度"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="4">
                <el-button type="primary" plain icon="place" @click="latShow = true">
                  打开地图复制坐标
                </el-button>
              </el-col>
            </el-row>
          </div>

          <!-- <el-form-item label="店铺经度" prop="lat">
          <el-row>
            <el-col :span="9" v-if="state.form.provinces">
              <el-input :value="`${state.form.provinces}-${state.form.cities}-${state.form.districts}`" disabled />
            </el-col>
            <el-col :span="4" v-if="state.form.lng">
              <el-input v-model="state.form.lng" placeholder="经度" disabled></el-input>
            </el-col>
            <el-col :span="4" v-if="state.form.lng">
              <el-input v-model="state.form.lat" placeholder="纬度" disabled></el-input>
            </el-col>
            <el-col :span="4">
              <el-button type="primary" plain icon="place" @click="state.showLocation = true">
                选择坐标
              </el-button>
            </el-col>
          </el-row>
        </el-form-item> -->
          <el-form-item label="店铺详细地址">
            <el-input type="textarea" v-model="state.form.address" placeholder="请输入门店详细地址"></el-input>
          </el-form-item>
          <el-form-item label="店铺简介">
            <el-input type="textarea" v-model="state.form.detail" placeholder="请输入店铺简介"></el-input>
          </el-form-item>
          <el-form-item label="状态">
            <el-radio-group v-model="state.form.status">
              <el-radio :value="1">开启</el-radio>
              <el-radio :value="0">关闭</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
      </div>
      <el-dialog title="选择地址" v-model="state.showLocation" :modal="false" :modal-append-to-body="false">
        <div class="map_box">
          <div class="map">
            <el-amap ref="map" :center="state.amapOptions.center" @init="mapInit">
              <el-amap-marker :position="state.amapOptions.center"></el-amap-marker>
            </el-amap>
          </div>
          <div class="search_box">
            <el-input v-model="state.searchOption.keyword" placeholder="请输入关键字" @focus="state.searchOption.focus = true"
              @blur="autoCompleteSearchBlur" @input="autoCompleteSearch(state.searchOption.keyword)">
              <template #append>
                <el-button type="primary" @click="placeSearchSearch(state.searchOption.keyword)">
                  搜索
                </el-button>
              </template>
            </el-input>
            <div class="list" v-if="state.searchOption.focus && state.searchOption.show">
              <div class="item" @click="autoCompleteListClick(item)" v-for="item in state.autoCompleteList"
                :key="item.id">
                {{ item.name }}
              </div>
            </div>
          </div>

          <div class="search_wrap">
            <div class="item" v-for="item in state.locationSearchList" :key="item.id">
              <div class="left">
                <div class="name">{{ item.name }}-{{ item.address }}</div>
                <div class="location">经纬度：{{ item.location.lng }},{{ item.location.lat }}</div>
              </div>
              <div class="btn">
                <el-button type="primary" @click="selectLocationHandle(item)">选择</el-button>
              </div>
            </div>
          </div>
        </div>
      </el-dialog>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="close">取消</el-button>
          <el-button type="primary" @click="submitHandle" :loading="state.formLoading">
            <span v-if="!state.formLoading">保存</span>
            <span v-else>保存中...</span>
          </el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog title="坐标搜索" v-model="latShow" width="60vw">
      <iframe style="width: 100%; height: 60vh" src="https://lbs.baidu.com/maptool/getpoint" frameborder="0"></iframe>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="latShow = false">取消</el-button>
          <el-button type="primary" @click="latConfirm">确认</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { getToken } from "@/utils/auth";
import uploadImg from "@/assets/images/upload.png";
import { ElAmap } from "@vuemap/vue-amap";
import { initMapLoad } from "@/utils/mapLoadUtil";
import { ElNotification } from "element-plus";
// { geocode, ShopApi.getList }
import ShopApi from "@/api/account/shop";
import activeDate from "./activeDate.vue";

const latShow = ref(false);
const validateLogo = (rule, value, callback) => {
  if (!state.form.logo) {
    callback(new Error("请上传门店logo"));
  } else {
    callback();
  }
};
async function latConfirm() {
  //js获取当前剪贴板内容
  try {
    // 核心：异步读取剪贴板文本内容
    const clipboardText = await navigator.clipboard.readText();

    // 显示获取到的内容
    console.log("剪贴板内容：", clipboardText);
    if (clipboardText && clipboardText.indexOf(",") > 0) {
      const latLng = clipboardText.split(",");
      state.form.lat = latLng[1];
      state.form.lng = latLng[0];
      latShow.value = false;
    } else[ElMessage.error("请搜索地址后复制经纬度")];
  } catch (err) {
    // 捕获异常（用户拒绝权限、浏览器不支持、非交互上下文等）
    console.error("获取剪贴板失败：", err);
  }
}
function openMap() {
  window.open("https://lbs.baidu.com/maptool/getpoint");
}

const state = reactive({
  uploadImg: uploadImg,
  dialogVisible: false,
  showLocation: false,
  showUpload: false,
  uploadIndex: 1,
  startTime: "",
  endTime: "",
  formLoading: false,
  form: {
    id: null,
    shopName: "",
    mainId: "",
    shopType: "only",
    tubeType: 0,
    registerType: "before",
    profiles: "release",
    activateDuration: "", // 激活时长
    activateAmount: "", // 激活费用
    accountName: "",
    accountPwd: "",
    phone: "",
    supportDeviceNumber: 1,
    lat: "",
    lng: "",
    address: "",
    detail: "",
    status: 1,
    logo: "",
    frontImg: "",
    provinces: "",
    cities: "",
    districts: "",
    chainName: "",
    isHeadShop: 0,
  },
  type: "",
  resetForm: "",
  rules: {
    activateDuration: [
      {
        required: true,
        message: "请选择激活时长",
        trigger: "change",
      },
    ],
    shopName: [
      {
        required: true,
        message: "请输入店铺名称",
        trigger: "blur",
      },
    ],
    isHeadShop: [
      {
        required: true,
        message: " ",
        trigger: "blur",
      },
    ],
    mainId: [
      {
        required: true,
        message: " ",
        trigger: "blur",
      },
    ],
    districts: [
      {
        required: true,
        message: "请选择店铺地址",
        trigger: "change",
      },
    ],
    lng: [
      {
        required: true,
        message: "请选择坐标",
        trigger: "change",
      },
    ],
    lat: [
      {
        required: true,
        message: "请选择坐标",
        trigger: "change",
      },
    ],
    logo: [
      {
        required: true,
        validator: validateLogo,
        trigger: "请上传门店logo",
      },
    ],
    accountName: [
      {
        required: true,
        message: "请输入账号",
        trigger: "change",
      },
    ],
    accountPwd: [
      {
        required: true,
        message: "请输入账号密码",
        trigger: "change",
      },
    ],
    phone: [
      {
        required: true,
        message: "请输入联系电话",
        trigger: "change",
      },
    ],
    // 密码长度6-18位，需包含字母、数字、特殊符号中至少两种
    accountPwd: [
      {
        required: true,
        message: "请输入登录密码",
        trigger: "blur",
      },
      {
        min: 6,
        max: 18,
        message: "密码长度应为6-18位",
        trigger: "blur",
      },
      {
        pattern: /^(?![0-9]+$)(?![a-zA-Z]+$)(?![^\da-zA-Z]+$).{6,}$/,
        message: "密码需包含字母、数字、特殊符号中至少两种",
        trigger: "blur",
      },
    ]
  },
  fileList: [],
  files: [],
  headers: {
    Authorization: getToken(),
  },
  searchOption: {
    city: "西安",
    citylimit: false,
    keyword: "",
    show: false,
    focus: false,
  },
  autoCompleteList: [],
  locationSearchList: [],
  amapOptions: {
    center: [108.946465, 34.347984],
    position: [],
  },
  shopListLoading: false,
  shopList: [],
  isEdit: false,
});
onBeforeMount(async () => {
  const res = await initMapLoad();
});
onMounted(() => {
  state.resetForm = { ...state.form };
});

// 获取商家列表
async function getTableData(query = "") {
  console.log(123);
  state.shopListLoading = true;
  try {
    const res = await ShopApi.getList({
      page: 1,
      size: 100,
      shopName: query,
      type: "only",
      isHeadShop: 1,
    });
    state.shopListLoading = false;
    state.shopList = res.records;
  } catch (error) {
    state.shopListLoading = false;
    console.log(error);
  }
}

// 确认地址选择
async function selectLocationHandle(item) {
  console.log(item);
  state.form.lng = item.location.lng;
  state.form.lat = item.location.lat;
  state.form.address = item.address;
  state.showLocation = false;

  const position = `${item.location.lng},${item.location.lat}`;

  state.form.provinces = item.pname;
  state.form.cities = item.cityname;
  state.form.districts = item.adname;
}
const emits = defineEmits(["close", "success"]);
const refForm = ref(null);
// 保存
function submitHandle() {
  refForm.value.validate(async (valid) => {
    if (valid) {
      state.formLoading = true;
      try {
        state.form.id ? await ShopApi.edit(state.form) : await ShopApi.add(state.form);
        emits("success");
        state.formLoading = false;
        ElNotification({
          title: "成功",
          message: `${state.form.id ? "编辑" : "添加"}成功`,
          type: "success",
        });
        close();
        location.reload();
      } catch (error) {
        state.formLoading = false;
        console.log(error);
      }
    }
  });
}
function handleSuccess(response, file, fileList) {
  // const uid = file.uid
  // const id = response.id
  // this.files.push({ uid, id })
  console.log("上传成功", response);
  state.files = response.data;
}

function show(obj, type) {
  getTableData();
  state.dialogVisible = true;
  if (obj && obj.id) {
    console.log(obj);
    state.form = { ...obj };
    state.form.accountName = obj.account ? obj.account : "";
  }
  if (obj && obj.mainId) {
    Object.assign(state.form, obj);
  }
  if (type) {
    state.type = type;
  }
  console.log(state.form);
  console.log(state.type);
  if (state.form.shopType != "only") {
    state.isEdit = true;
  }
  for (let key in state.rules) {
    if (key === "accountName") {
      if (obj.id) {
        state.rules[key][0].required = false;
      } else {
        state.rules[key][0].required = true;
      }
    }
  }
  console.log(state.rules);
}
function close() {
  state.dialogVisible = false;
  state.form = { ...state.resetForm };
  state.type = "";
  state.isEdit = false;
}
function reset() {
  state.form = { ...state.resetForm };
  state.type = "";
  state.isEdit = false;
}

let ElMap = undefined;
let placeSearch = undefined;
let autoComplete = undefined;
let PlaceSearchIndex = 1;

function autoCompleteSearchBlur() {
  setTimeout(() => {
    state.searchOption.show = false;
  }, 200);
}

function autoCompleteSearch(keyword) {
  if (keyword === "") {
    state.autoCompleteList = [];
    return;
  }
  autoComplete.search(keyword, function (status, result) {
    if (status === "complete" && result.info === "OK") {
      // 搜索成功时，result即是对应的匹配数据
      console.log(result);
      state.searchOption.show = true;
      state.autoCompleteList = result.tips;
    }
  });
}
function autoCompleteListClick(item) {
  console.log(item);
  state.searchOption.keyword = item.name;
  state.autoCompleteList = [];
  placeSearchSearch(item.name);
}
function placeSearchSearch(keyword) {
  PlaceSearchIndex = 1;
  if (keyword === "") {
    state.locationSearchList = [];
    return;
  }
  //  关键字查询
  placeSearch.search(keyword, (status, result) => {
    console.log(status);
    console.log(result);
    state.locationSearchList = result.poiList.pois;
  });
}
function mapInit(map) {
  map.plugin(["AMap.PlaceSearch", "AMap.AutoComplete", "AMap.ToolBar"], () => {
    const toolBar = new AMap.ToolBar();
    map.addControl(toolBar);
    // 注意：输入提示插件2.0版本需引入AMap.AutoComplete，而1.4版本应使用AMap.Autocomplete
    // 实例化AutoComplete
    var autoOptions = {
      city: "西安",
    };
    autoComplete = new AMap.AutoComplete(autoOptions);

    //构造地点查询类
    placeSearch = new AMap.PlaceSearch({
      pageSize: 10, // 单页显示结果条数
      pageIndex: PlaceSearchIndex, // 页码
      city: "西安", // 兴趣点城市
      citylimit: true, //是否强制限制在设置的城市内搜索
      map: map, // 展现结果的地图实例
      // panel: "search_wrap", // 结果列表将在此容器中进行展示。
      autoFitView: true, // 是否自动调整地图视野使绘制的 Marker点都处于视口的可见范围
    });
  });

  ElMap = map;
}

defineExpose({
  show,
  close,
  reset,
});
</script>

<style scoped lang="scss">
.map_box {
  width: 100%;
  position: relative;

  .map {
    height: 300px;
  }

  .search_box {
    position: absolute;
    top: 10px;
    left: 10px;
    z-index: 3000;

    .list {
      background-color: #fff;

      .item {
        height: 40px;
        line-height: 40px;
        box-shadow: 0 1px 1px rgba(0, 0, 0, 0.1);
        padding: 0 10px;
        cursor: pointer;

        &:hover {
          background-color: #eee;
        }
      }
    }
  }

  .search_wrap {
    padding: 6px 0;

    .item {
      display: flex;
      padding: 12px 0;

      .left {
        flex: 1;
        display: flex;
        flex-direction: column;
        padding-right: 20px;

        .location {
          color: #999;
          padding-top: 4px;
        }
      }
    }
  }
}

.amap-sug-result {
  z-index: 2000;
}

.tips {
  margin-left: 10px;
}
</style>
