<template>
  <div class="pages-card">
    <div class="med-head" style="padding: 20px">
      <div class="title">站点设置</div>
    </div>

    <!-- 添加或修改站点设置对话框 -->
    <el-form ref="siteSettingFormRef" :model="form" :rules="rules" label-width="150px" style="width: 650px; padding: 20px">
      <el-form-item label="总控后台名称" prop="generalBackstageName">
        <el-input v-model="form.generalBackstageName" placeholder="请输入总控后台名称" :disabled="editBtn" />
      </el-form-item>
      <el-form-item label="门店后台名称" prop="storeBackstageName">
        <el-input v-model="form.storeBackstageName" placeholder="请输入门店后台名称" :disabled="editBtn" />
      </el-form-item>
      <el-form-item label="电话号码" prop="phonenumber">
        <el-input v-model="form.phonenumber" placeholder="请输入电话号码" :disabled="editBtn" />
      </el-form-item>
      <el-form-item label="商城提现手续费" prop="serviceCharge">
        <el-input v-model="form.serviceCharge" placeholder="请输入商城提现手续费" :disabled="editBtn" />
      </el-form-item>
      <el-form-item label="总控域名" prop="domainName">
        <el-input v-model="form.domainName" placeholder="请输入总控域名" :disabled="editBtn" />
      </el-form-item>
      <el-form-item label="圆形logo" prop="roundLogo">
        <div class="image-upload-container">
          <div class="upload-item" v-if="form.roundLogo">
            <el-image :src="form.roundLogo" fit="cover" class="upload-image" />
            <div class="upload-mask">
              <el-icon @click="!editBtn && openFileSelector('roundLogo')" :class="{'disabled': editBtn}" class="mask-icon">
                <Edit />
              </el-icon>
              <el-icon @click="!editBtn && (form.roundLogo = '')" :class="{'disabled': editBtn}" class="mask-icon">
                <Delete />
              </el-icon>
            </div>
          </div>
          <div v-else class="upload-placeholder" @click="!editBtn && openFileSelector('roundLogo')" :class="{'disabled': editBtn}">
            <el-icon class="upload-icon"><Plus /></el-icon>
            <div class="upload-hint">建议尺寸</div>
            <div class="upload-size">200 × 200</div>
          </div>
        </div>
      </el-form-item>
      <el-form-item label="用户后台登录" prop="userBackstageLogin">
        <div class="image-upload-container">
          <div class="upload-item" v-if="form.userBackstageLogin">
            <el-image :src="form.userBackstageLogin" fit="cover" class="upload-image" />
            <div class="upload-mask">
              <el-icon @click="!editBtn && openFileSelector('userBackstageLogin')" :class="{'disabled': editBtn}" class="mask-icon">
                <Edit />
              </el-icon>
              <el-icon @click="!editBtn && (form.userBackstageLogin = '')" :class="{'disabled': editBtn}" class="mask-icon">
                <Delete />
              </el-icon>
            </div>
          </div>
          <div v-else class="upload-placeholder" @click="!editBtn && openFileSelector('userBackstageLogin')" :class="{'disabled': editBtn}">
            <el-icon class="upload-icon"><Plus /></el-icon>
            <div class="upload-hint">建议尺寸</div>
            <div class="upload-size">200 × 60</div>
          </div>
        </div>
      </el-form-item>
      <el-form-item label="用户后台应用" prop="userBackstageApp">
        <div class="image-upload-container">
          <div class="upload-item" v-if="form.userBackstageApp">
            <el-image :src="form.userBackstageApp" fit="cover" class="upload-image" />
            <div class="upload-mask">
              <el-icon @click="!editBtn && openFileSelector('userBackstageApp')" :class="{'disabled': editBtn}" class="mask-icon">
                <Edit />
              </el-icon>
              <el-icon @click="!editBtn && (form.userBackstageApp = '')" :class="{'disabled': editBtn}" class="mask-icon">
                <Delete />
              </el-icon>
            </div>
          </div>
          <div v-else class="upload-placeholder" @click="!editBtn && openFileSelector('userBackstageApp')" :class="{'disabled': editBtn}">
            <el-icon class="upload-icon"><Plus /></el-icon>
            <div class="upload-hint">建议尺寸</div>
            <div class="upload-size">200 × 60</div>
          </div>
        </div>
      </el-form-item>
      <el-form-item label="总后台登录" prop="generalBackstageLogin">
        <div class="image-upload-container">
          <div class="upload-item" v-if="form.generalBackstageLogin">
            <el-image :src="form.generalBackstageLogin" fit="cover" class="upload-image" />
            <div class="upload-mask">
              <el-icon @click="!editBtn && openFileSelector('generalBackstageLogin')" :class="{'disabled': editBtn}" class="mask-icon">
                <Edit />
              </el-icon>
              <el-icon @click="!editBtn && (form.generalBackstageLogin = '')" :class="{'disabled': editBtn}" class="mask-icon">
                <Delete />
              </el-icon>
            </div>
          </div>
          <div v-else class="upload-placeholder" @click="!editBtn && openFileSelector('generalBackstageLogin')" :class="{'disabled': editBtn}">
            <el-icon class="upload-icon"><Plus /></el-icon>
            <div class="upload-hint">建议尺寸</div>
            <div class="upload-size">200 × 60</div>
          </div>
        </div>
      </el-form-item>
      <el-form-item label="总后台应用" prop="generalBackstageApp">
        <div class="image-upload-container">
          <div class="upload-item" v-if="form.generalBackstageApp">
            <el-image :src="form.generalBackstageApp" fit="cover" class="upload-image" />
            <div class="upload-mask">
              <el-icon @click="!editBtn && openFileSelector('generalBackstageApp')" :class="{'disabled': editBtn}" class="mask-icon">
                <Edit />
              </el-icon>
              <el-icon @click="!editBtn && (form.generalBackstageApp = '')" :class="{'disabled': editBtn}" class="mask-icon">
                <Delete />
              </el-icon>
            </div>
          </div>
          <div v-else class="upload-placeholder" @click="!editBtn && openFileSelector('generalBackstageApp')" :class="{'disabled': editBtn}">
            <el-icon class="upload-icon"><Plus /></el-icon>
            <div class="upload-hint">建议尺寸</div>
            <div class="upload-size">200 × 60</div>
          </div>
        </div>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm" v-hasPermi="['system:siteSetting:add']" v-if="!editBtn">
          &nbsp;&nbsp;&nbsp;保存设置&nbsp;&nbsp;&nbsp;
        </el-button>
        <el-button type="primary" @click="editBtn = false" v-hasPermi="['system:siteSetting:add']" v-if="editBtn">
          &nbsp;&nbsp;&nbsp;编辑设置&nbsp;&nbsp;&nbsp;
        </el-button>
      </el-form-item>
    </el-form>

    <!-- 文件选择器 -->
    <FileSelector
      v-model="showFileSelector"
      :allowed-types="[1]"
      :multiple="false"
      :title="fileSelectorTitle"
      @confirm="handleFileSelect"
    />
  </div>
</template>

<script setup name="SiteSetting" lang="ts">
import { addSiteSetting, updateSiteSetting, getSiteSettingData } from '@/api/setting/siteSetting/index';
import { SiteSettingQuery, SiteSettingForm } from '@/api/setting/siteSetting/types';
import { useSiteSettingStore } from '@/store/modules/siteSetting';
import emitter from '@/utils/eventBus';
import FileSelector from '@/components/FileSelector/index.vue';
import { Plus, Edit, Delete } from '@element-plus/icons-vue';

const siteSettingStore = useSiteSettingStore();
const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const buttonLoading = ref(false);
const loading = ref(true);
const editBtn = ref<boolean>(true);

// 文件选择器相关
const showFileSelector = ref(false);
const currentField = ref<string>('');
const fileSelectorTitle = ref('选择图片');

const siteSettingFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: SiteSettingForm = {
  id: undefined,
  generalBackstageName: undefined,
  storeBackstageName: undefined,
  phonenumber: undefined,
  serviceCharge: undefined,
  domainName: undefined,
  roundLogo: undefined,
  userBackstageLogin: undefined,
  userBackstageApp: undefined,
  generalBackstageLogin: undefined,
  generalBackstageApp: undefined,
  status: undefined,
  remark: undefined
};
const data = reactive<PageData<SiteSettingForm, SiteSettingQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    id: undefined,
    generalBackstageName: undefined,
    storeBackstageName: undefined,
    phonenumber: undefined,
    serviceCharge: undefined,
    domainName: undefined,
    roundLogo: undefined,
    userBackstageLogin: undefined,
    userBackstageApp: undefined,
    generalBackstageLogin: undefined,
    generalBackstageApp: undefined,
    status: undefined,
    params: {}
  },
  rules: {
    generalBackstageName: [{ required: true, message: '总控后台名称不能为空', trigger: 'blur' }],
    storeBackstageName: [{ required: true, message: '门店后台名称不能为空', trigger: 'blur' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询站点设置列表 */
const getList = async () => {
  loading.value = true;
  const res = await getSiteSettingData();
  if (res.data) {
    form.value = res.data;
    siteSettingStore.setSiteSettingInfo(res.data);
  }
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  siteSettingFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 提交按钮 */
const submitForm = () => {
  siteSettingFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateSiteSetting(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addSiteSetting(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
      // ✅ 触发全局事件，通知其他组件更新
      emitter.emit('siteSettingUpdated');
    }
  });
};

/** 打开文件选择器 */
const openFileSelector = (field: string) => {
  currentField.value = field;
  // 根据不同字段设置不同的标题
  const titleMap = {
    'roundLogo': '选择圆形Logo',
    'userBackstageLogin': '选择用户后台登录Logo',
    'userBackstageApp': '选择用户后台应用Logo',
    'generalBackstageLogin': '选择总后台登录Logo',
    'generalBackstageApp': '选择总后台应用Logo'
  };
  fileSelectorTitle.value = titleMap[field] || '选择图片';
  showFileSelector.value = true;
};

/** 处理文件选择 */
const handleFileSelect = (files: any[]) => {
  if (files && files.length > 0) {
    const file = files[0];
    // 将选中的文件URL赋值给对应的表单字段
    form.value[currentField.value] = file.url || file.path;
  }
};

onMounted(() => {
  getList();
});
</script>

<style scoped lang="scss">
.image-upload-container {
  display: inline-block;
}

.upload-item {
  position: relative;
  width: 148px;
  height: 148px;
  border-radius: 6px;
  overflow: hidden;
  border: 1px solid #dcdfe6;
  cursor: pointer;
  
  .upload-image {
    width: 100%;
    height: 100%;
  }
  
  .upload-mask {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.5);
    display: flex;
    justify-content: center;
    align-items: center;
    gap: 15px;
    opacity: 0;
    transition: opacity 0.3s;
    
    .mask-icon {
      font-size: 20px;
      color: #fff;
      cursor: pointer;
      transition: transform 0.3s;
      
      &:hover {
        transform: scale(1.2);
      }
      
      &.disabled {
        cursor: not-allowed;
        opacity: 0.5;
      }
    }
  }
  
  &:hover .upload-mask {
    opacity: 1;
  }
}

.upload-placeholder {
  width: 148px;
  height: 148px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  background-color: #fafafa;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  transition: border-color 0.3s;
  gap: 6px;
  
  .upload-icon {
    font-size: 28px;
    color: #8c939d;
  }
  
  .upload-hint {
    font-size: 12px;
    color: #8c939d;
    margin-top: 4px;
  }
  
  .upload-size {
    font-size: 12px;
    color: #606266;
    font-weight: 500;
  }
  
  &:hover:not(.disabled) {
    border-color: #409eff;
    
    .upload-icon {
      color: #409eff;
    }
    
    .upload-hint {
      color: #409eff;
    }
    
    .upload-size {
      color: #409eff;
    }
  }
  
  &.disabled {
    cursor: not-allowed;
    background-color: #f5f7fa;
    
    .upload-icon {
      color: #c0c4cc;
    }
    
    .upload-hint {
      color: #c0c4cc;
    }
    
    .upload-size {
      color: #c0c4cc;
    }
  }
}
</style>
