<template>
  <div class="setting-container">
    <el-tabs v-model="activeId" class="premium-tabs" @tab-change="handleTabChange">
      <el-tab-pane label="履约守护" :name="1" />
      <el-tab-pane label="好萌友" :name="2" />
    </el-tabs>

    <div class="tab-content">
      <el-form ref="customerFormRef" :model="form" :rules="rules" label-width="160px" class="premium-setting-form">
        <el-form-item label="客服微信号：" prop="wechatAccount">
          <el-input v-model="form.wechatAccount" placeholder="请输入客服微信号" class="config-input" />
        </el-form-item>

        <el-form-item label="客服电话：" prop="phoneNumber">
          <el-input v-model="form.phoneNumber" placeholder="请输入客服联系电话" class="config-input" />
        </el-form-item>

        <el-row>
          <el-col :span="12">
            <el-form-item label="客服开始时间：" prop="startServiceTime">
              <el-time-picker
                v-model="form.startServiceTime"
                placeholder="选择开始时间"
                format="HH:mm"
                value-format="HH:mm"
                class="config-time-picker"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="客服结束时间：" prop="endServiceTime">
              <el-time-picker
                v-model="form.endServiceTime"
                placeholder="选择结束时间"
                format="HH:mm"
                value-format="HH:mm"
                class="config-time-picker"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="企微链接：" prop="enterpriseWechatLink">
          <el-input v-model="form.enterpriseWechatLink" placeholder="请输入企业微信链接" class="config-input" />
        </el-form-item>

        <el-form-item label="客服二维码：" prop="qrCode">
          <image-upload v-model="form.qrCode" :limit="1" :can-delete="false" />
          <div class="form-tip">支持 jpg/png 格式</div>
        </el-form-item>

        <el-form-item class="action-item">
          <el-button type="primary" class="save-btn" :loading="loading" @click="submitForm">保存修改</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup lang="ts">
// @Author: Antigravity
import { getCustomerServiceSetting, updateCustomerServiceSetting } from '@/api/system/customerServiceSetting';
import { CustomerServiceSettingForm } from '@/api/system/customerServiceSetting/types';
import ImageUpload from '@/components/ImageUpload/index.vue';
import { ref, onMounted, getCurrentInstance, ComponentInternalInstance } from 'vue';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const loading = ref(false);
const customerFormRef = ref<any>();
const activeId = ref(1);

const form = ref<any>({
  id: 1,
  wechatAccount: '',
  phoneNumber: '',
  startServiceTime: '',
  endServiceTime: '',
  qrCode: undefined,
  enterpriseWechatLink: ''
});

const rules = {
  wechatAccount: [{ required: true, message: "微信号不能为空", trigger: "blur" }],
  phoneNumber: [{ required: true, message: "电话不能为空", trigger: "blur" }],
  startServiceTime: [{ required: true, message: "开始时间不能为空", trigger: "change" }],
  endServiceTime: [{ required: true, message: "结束时间不能为空", trigger: "change" }],
  qrCode: [{ required: true, message: "二维码不能为空", trigger: "change" }]
};

const handleTabChange = (val: any) => {
  activeId.value = val;
  loadData();
};

const loadData = async () => {
  try {
    const res = await getCustomerServiceSetting(activeId.value);
    if (res.code === 200) {
      if (res.data) {
        form.value = { ...res.data };
        // 提取时分：后端返回 1970-01-01 08:00:00，前端需要 HH:mm
        if (form.value.startServiceTime && form.value.startServiceTime.includes(' ')) {
          form.value.startServiceTime = form.value.startServiceTime.split(' ')[1].substring(0, 5);
        }
        if (form.value.endServiceTime && form.value.endServiceTime.includes(' ')) {
          form.value.endServiceTime = form.value.endServiceTime.split(' ')[1].substring(0, 5);
        }
        if (typeof form.value.qrCode === 'number') form.value.qrCode = String(form.value.qrCode);
      } else {
        form.value = {
          id: activeId.value,
          wechatAccount: '',
          phoneNumber: '',
          startServiceTime: '',
          endServiceTime: '',
          qrCode: undefined,
          enterpriseWechatLink: ''
        };
      }
    }
  } catch (err) {}
};

const submitForm = () => {
  customerFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      loading.value = true;
      try {
        const submitData: CustomerServiceSettingForm = {
            id: activeId.value,
            wechatAccount: form.value.wechatAccount,
            phoneNumber: form.value.phoneNumber,
            // 提交时补全日期前缀，以匹配后端的日期时间格式
            startServiceTime: form.value.startServiceTime ? (form.value.startServiceTime.includes(' ') ? form.value.startServiceTime : `1970-01-01 ${form.value.startServiceTime}:00`) : '',
            endServiceTime: form.value.endServiceTime ? (form.value.endServiceTime.includes(' ') ? form.value.endServiceTime : `1970-01-01 ${form.value.endServiceTime}:00`) : '',
            qrCode: form.value.qrCode,
            enterpriseWechatLink: form.value.enterpriseWechatLink
        };
        await updateCustomerServiceSetting(submitData);
        proxy?.$modal.msgSuccess("保存成功");
        loadData();
      } finally {
        loading.value = false;
      }
    }
  });
};

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

<style scoped lang="scss">
.setting-container {
  padding-top: 10px;
}

.premium-tabs {
  margin-bottom: 20px;
  :deep(.el-tabs__header) {
    border-bottom: 1px solid #e5e6eb;
  }
}

.tab-content {
  padding: 10px 0;
}

.premium-setting-form {
  :deep(.el-form-item__label) {
    font-weight: 500;
    color: #4e5969;
    padding-right: 24px;
  }

  .config-input {
    max-width: 440px;
    :deep(.el-input__wrapper) {
      box-shadow: 0 0 0 1px #e5e6eb inset;
      padding: 4px 12px;
      border-radius: 6px;

      &.is-focus {
        box-shadow: 0 0 0 1px #409eff inset;
      }
    }
  }

  .config-time-picker {
    max-width: 180px;
    :deep(.el-input__wrapper) {
      box-shadow: 0 0 0 1px #e5e6eb inset;
      border-radius: 6px;
    }
  }

  .form-tip {
    font-size: 13px;
    color: #86909c;
    margin-top: 8px;
    line-height: 1.4;
    display: block;
    width: 100%;
  }

  .action-item {
    margin-top: 40px;
  }

  .save-btn {
    padding: 12px 32px;
    height: auto;
    font-size: 15px;
    font-weight: 500;
    border-radius: 6px;
    box-shadow: 0 4px 10px rgba(64, 158, 255, 0.2);
  }
}
</style>
