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

    <el-form ref="sysAgentSetFormRef" class="form-edit" :model="form" :rules="rules" label-width="150px" style="width: 650px; padding: 20px">
      <el-form-item label="代理后台名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入代理后台名称" :disabled="editBtn" />
      </el-form-item>
      <el-form-item label="客服名称" prop="serviceName">
        <el-input v-model="form.serviceName" placeholder="请输入客服名称" :disabled="editBtn" />
      </el-form-item>
      <el-form-item label="客服电话" prop="servicePhone">
        <el-input v-model="form.servicePhone" placeholder="请输入客服电话" :disabled="editBtn" />
      </el-form-item>
      <el-form-item label="客服二维码" prop="serviceQrCode">
        <div class="image-upload-container">
          <div class="upload-item" v-if="form.serviceQrCode">
            <el-image :src="form.serviceQrCode" fit="cover" class="upload-image" />
            <div class="upload-mask">
              <el-icon @click="!editBtn && openFileSelector('serviceQrCode')" :class="{'disabled': editBtn}" class="mask-icon">
                <Edit />
              </el-icon>
              <el-icon @click="!editBtn && (form.serviceQrCode = '')" :class="{'disabled': editBtn}" class="mask-icon">
                <Delete />
              </el-icon>
            </div>
          </div>
          <div v-else class="upload-placeholder" @click="!editBtn && openFileSelector('serviceQrCode')" :class="{'disabled': editBtn}">
            <el-icon class="upload-icon"><Plus /></el-icon>
            <div class="upload-hint">建议尺寸</div>
            <div class="upload-size">430 × 430</div>
          </div>
        </div>
      </el-form-item>
      <el-form-item label="代理后台登录logo" prop="loginLogo">
        <div class="image-upload-container">
          <div class="upload-item" v-if="form.loginLogo">
            <el-image :src="form.loginLogo" fit="cover" class="upload-image" />
            <div class="upload-mask">
              <el-icon @click="!editBtn && openFileSelector('loginLogo')" :class="{'disabled': editBtn}" class="mask-icon">
                <Edit />
              </el-icon>
              <el-icon @click="!editBtn && (form.loginLogo = '')" :class="{'disabled': editBtn}" class="mask-icon">
                <Delete />
              </el-icon>
            </div>
          </div>
          <div v-else class="upload-placeholder" @click="!editBtn && openFileSelector('loginLogo')" :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="代理后台应用logo" prop="appLogo">
        <div class="image-upload-container">
          <div class="upload-item" v-if="form.appLogo">
            <el-image :src="form.appLogo" fit="cover" class="upload-image" />
            <div class="upload-mask">
              <el-icon @click="!editBtn && openFileSelector('appLogo')" :class="{'disabled': editBtn}" class="mask-icon">
                <Edit />
              </el-icon>
              <el-icon @click="!editBtn && (form.appLogo = '')" :class="{'disabled': editBtn}" class="mask-icon">
                <Delete />
              </el-icon>
            </div>
          </div>
          <div v-else class="upload-placeholder" @click="!editBtn && openFileSelector('appLogo')" :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:sysAgentSet:add']" v-if="!editBtn">
          &nbsp;&nbsp;&nbsp;保存设置&nbsp;&nbsp;&nbsp;
        </el-button>
        <el-button type="primary" @click="editBtn = false" v-hasPermi="['system:sysAgentSet: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="SysAgentSet" lang="ts">
import { getSysAgentSet, delSysAgentSet, addSysAgentSet, updateSysAgentSet, getAgentSetData } from '@/api/system/sysAgentSet/index';
import { SysAgentSetVO, SysAgentSetQuery, SysAgentSetForm } from '@/api/system/sysAgentSet/types';
import FileSelector from '@/components/FileSelector/index.vue';
import { Plus, Edit, Delete } from '@element-plus/icons-vue';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { sys_normal_disable } = toRefs<any>(proxy?.useDict('sys_normal_disable'));

const editBtn = ref<boolean>(true);
const buttonLoading = ref(false);
const loading = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

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

const queryFormRef = ref<ElFormInstance>();
const sysAgentSetFormRef = ref<ElFormInstance>();

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

const initFormData: SysAgentSetForm = {
  id: undefined,
  name: undefined,
  serviceId: undefined,
  serviceName: undefined,
  servicePhone: undefined,
  serviceQrCode: undefined,
  loginLogo: undefined,
  appLogo: undefined,
  status: undefined
};
const data = reactive<PageData<SysAgentSetForm, SysAgentSetQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    id: undefined,
    params: {}
  },
  rules: {
    name: [{ required: true, message: '代理后台名称不能为空', trigger: 'blur' }],
    serviceName: [{ required: true, message: '客服名称不能为空', trigger: 'blur' }],
    servicePhone: [{ required: true, message: '客服电话不能为空', trigger: 'blur' }]
    // serviceQrCode: [{ required: true, message: '客服二维码不能为空', trigger: 'blur' }],
    // loginLogo: [{ required: true, message: '代理后台登录logo不能为空', trigger: 'blur' }],
    // appLogo: [{ required: true, message: '代理后台应用logo不能为空', trigger: 'blur' }]
  }
});

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

/** 查询代理后台设置列表 */
const getList = async () => {
  loading.value = true;
  const res = await getAgentSetData();
  if (res.data) {
    form.value = res.data;
  }
};

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

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

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

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: SysAgentSetVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加代理后台设置';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: SysAgentSetVO) => {
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getSysAgentSet(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改代理后台设置';
};

/** 提交按钮 */
const submitForm = () => {
  sysAgentSetFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateSysAgentSet(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addSysAgentSet(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: SysAgentSetVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除代理后台设置编号为"' + _ids + '"的数据项？').finally(() => (loading.value = false));
  await delSysAgentSet(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'system/sysAgentSet/export',
    {
      ...queryParams.value
    },
    `sysAgentSet_${new Date().getTime()}.xlsx`
  );
};

/** 打开文件选择器 */
const openFileSelector = (field: string) => {
  currentField.value = field;
  // 根据不同字段设置不同的标题
  const titleMap = {
    'serviceQrCode': '选择客服二维码',
    'loginLogo': '选择登录Logo',
    'appLogo': '选择应用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>
