<template>
  <div class="page-container">
    <el-card shadow="never">
      <template #header>
        <div class="card-header">
          <span>门店信息设置</span>
          <el-select v-model="currentStoreId" placeholder="选择门店" @change="handleStoreChange" style="width: 250px">
            <el-option v-for="store in stores" :key="store.id" :label="store.name" :value="store.id" />
          </el-select>
        </div>
      </template>

      <el-form :model="storeForm" label-width="120px" class="store-form">
        <!-- Logo -->
        <el-form-item label="门店Logo">
          <el-upload class="avatar-uploader" action="#" :show-file-list="false" :auto-upload="false" :on-change="handleLogoChange">
            <el-avatar v-if="storeForm.logo" :size="100" shape="square" :src="storeForm.logo" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>

        <!-- License -->
        <el-form-item label="营业执照" required>
          <el-upload action="#" :show-file-list="false" :auto-upload="false" :on-change="handleLicenseChange">
            <el-image style="width: 150px; height: 100px; border-radius: 4px; border: 1px solid #dcdfe6" :src="storeForm.license" fit="cover">
              <template #error>
                <div
                  style="width: 100%; height: 100%; background: #f5f7fa; display: flex; justify-content: center; align-items: center; color: #dedfe0"
                >
                  <el-icon size="24"><Picture /></el-icon>
                </div>
              </template>
            </el-image>
          </el-upload>
        </el-form-item>

        <!-- Name -->
        <el-form-item label="门店名称" required>
          <el-input v-model="storeForm.name" style="width: 400px" disabled />
        </el-form-item>

        <!-- Services -->
        <el-form-item label="服务项目" required>
          <el-checkbox-group v-model="storeForm.services" disabled>
            <el-checkbox v-for="service in serviceOptions" :key="service.id" :label="service.id">
              {{ service.name }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>

        <!-- Category -->
        <el-form-item label="商户分类" required>
          <el-input v-model="storeForm.category" style="width: 400px" disabled />
        </el-form-item>

        <!--        &lt;!&ndash; Account &ndash;&gt;-->
        <!--        <el-form-item label="管理账号" required>-->
        <!--          <el-input v-model="storeForm.account" placeholder="用于后台登录" style="width: 400px" disabled />-->
        <!--        </el-form-item>-->

        <!--        &lt;!&ndash; Password &ndash;&gt;-->
        <!--        <el-form-item label="登录密码">-->
        <!--          <el-input v-model="storeForm.password" type="password" show-password placeholder="若留空则不修改密码" style="width: 400px" />-->
        <!--        </el-form-item>-->

        <!-- Business hours -->
        <el-form-item label="营业时间" required>
          <div style="width: 400px">
            <el-time-picker
              v-model="storeForm.businessHours"
              is-range
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              format="HH:mm"
              value-format="HH:mm"
              style="width: 100%"
            />
          </div>
        </el-form-item>

        <el-form-item label="联系人" required>
          <el-input v-model="storeForm.contactPerson" style="width: 400px" />
        </el-form-item>

        <el-form-item label="联系电话" required>
          <el-input v-model="storeForm.contactPhone" style="width: 400px" />
        </el-form-item>

        <!-- Valid Until -->
        <el-form-item label="有效期至">
          <el-input :model-value="storeForm.validUntil" disabled style="width: 400px" />
        </el-form-item>

        <!-- Address -->
        <el-form-item label="详细地址" required>
          <div style="width: 600px">
            <el-cascader
              v-model="storeForm.selectedArea"
              :options="regionData"
              placeholder="请选择省/市/区"
              style="width: 100%; margin-bottom: 10px"
              @change="handleAreaChange"
            />
            <el-input v-model="storeForm.address" type="textarea" placeholder="输入详细地址" />
            <div style="margin-top: 10px; text-align: right">
              <el-button type="warning" size="small" @click="handleGetLocation" icon="Location">获取经纬度</el-button>
            </div>
          </div>
        </el-form-item>

        <!-- Lat Lng -->
        <el-form-item label="经纬度">
          <div style="display: flex; gap: 10px; width: 600px">
            <el-input v-model="storeForm.longitude" placeholder="经度" readonly />
            <el-input v-model="storeForm.latitude" placeholder="纬度" readonly />
          </div>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleSave" size="large">保存修改</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { reactive, ref, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { Plus, Picture, Location } from '@element-plus/icons-vue';
import { listOnMerchantStoreInfo, getStoreInfo } from '@/api/system/store';
import { listOnStore } from '@/api/service/list';
import { regionData } from 'element-china-area-data';

const currentStoreId = ref('');

const stores = ref([]);
const serviceOptions = ref([]);

const storeForm = reactive({
  id: '',
  logo: '',
  license: '',
  name: '',
  services: [],
  category: '',
  account: '',
  password: '',
  contactPerson: '',
  contactPhone: '',
  businessHours: ['', ''],
  validUntil: '',
  address: '',
  longitude: '',
  latitude: '',
  areaCode: '',
  selectedArea: []
});

const getStoreList = async () => {
  try {
    const res = await listOnMerchantStoreInfo();
    const data = res.data;
    if (data && data.length > 0) {
      stores.value = data;
      currentStoreId.value = data[0].id;
      handleStoreChange(currentStoreId.value);
    }
  } catch (error) {
    console.error('获取门店列表失败:', error);
  }
};

const getServiceOptions = async () => {
  try {
    const res = await listOnStore();
    if (res.data) {
      serviceOptions.value = res.data;
    }
  } catch (error) {
    console.error('获取服务项目失败:', error);
  }
};

const handleStoreChange = async (val) => {
  if (!val) return;
  try {
    const res = await getStoreInfo(val);
    const data = res.data;
    if (data) {
      storeForm.id = data.id;
      storeForm.logo = data.logoUrl || '';
      storeForm.license = data.businessLicenseUrl || '';
      storeForm.name = data.name || '';
      storeForm.services = data.services || [];
      storeForm.category = data.tenantCatergoriesName || '';
      storeForm.contactPerson = data.contact || '';
      storeForm.contactPhone = data.contactNumber || '';

      const start = data.startBusinessTime ? data.startBusinessTime.split(' ')[1]?.substring(0, 5) : '';
      const end = data.endBusinessTime ? data.endBusinessTime.split(' ')[1]?.substring(0, 5) : '';
      storeForm.businessHours = [start, end];

      storeForm.validUntil = data.validity ? data.validity.split(' ')[0] : '';

      storeForm.address = data.detailAddress || '';
      storeForm.longitude = data.longitude ? String(data.longitude) : '';
      storeForm.latitude = data.latitude ? String(data.latitude) : '';
      storeForm.areaCode = data.areaCode || '';
      if (data.areaCode) {
        if (Array.isArray(data.areaCode)) {
          storeForm.selectedArea = data.areaCode;
        } else if (typeof data.areaCode === 'string') {
          storeForm.selectedArea = data.areaCode.split(',');
        }
      } else {
        storeForm.selectedArea = [];
      }
    }
  } catch (error) {
    console.error('获取详细信息失败:', error);
  }
};

onMounted(() => {
  getServiceOptions();
  getStoreList();
});

const handleLogoChange = (file) => {
  if (file && file.raw) {
    storeForm.logo = URL.createObjectURL(file.raw);
  }
};

const handleLicenseChange = (file) => {
  if (file && file.raw) {
    storeForm.license = URL.createObjectURL(file.raw);
  }
};

const handleAreaChange = (val) => {
  if (val && val.length > 0) {
    storeForm.areaCode = val.join(',');
  } else {
    storeForm.areaCode = '';
  }
};

const handleGetLocation = () => {
  if (!storeForm.selectedArea || storeForm.selectedArea.length === 0) {
    return ElMessage.warning('请先选择省市区');
  }
  if (!storeForm.address) {
    return ElMessage.warning('请先填写详细地址');
  }

  ElMessage.success('根据地址获取经纬度成功');
  storeForm.longitude = '116.452562';
  storeForm.latitude = '39.936404';
};

const handleSave = () => {
  ElMessage.success(`门店【${storeForm.name}】信息已更新`);
};
</script>

<style scoped>
.page-container {
  padding: 20px;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.store-form {
  margin-top: 20px;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  text-align: center;
  border: 1px dashed #d9d9d9;
  border-radius: 8px;
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
}
.avatar-uploader-icon:hover {
  border-color: #409eff;
}
</style>
