<template>
  <div class="app-container mall-setting-page">
    <el-form ref="form" :model="form" :rules="rules" label-width="180px">
      <!-- 页头说明 -->
      <el-card v-loading="loading" shadow="never" class="section-card">
        <div slot="header" class="card-header">
          <span>商城设置</span>
          <span class="header-tip">全平台商城设置，修改后对全站 C 端及商家发品生效</span>
        </div>
        <p class="page-desc">与「店铺设置」独立：本页维护备案、商品展示、订单时限与会员默认头像；支付超时关单请在订单参数中配置。</p>
      </el-card>

      <br/>

      <!-- 备案信息 -->
      <el-card shadow="never" class="section-card">
        <div slot="header">备案信息</div>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="ICP 备案号" prop="icpNo">
              <el-input v-model="form.icpNo" placeholder="如：京 ICP 备 xxxxx 号" maxlength="128" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="ICP 备案链接" prop="icpLink">
              <el-input v-model="form.icpLink" placeholder="https://..." maxlength="512" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="公安备案号" prop="psbNo">
              <el-input v-model="form.psbNo" placeholder="如：京公网安备 xxxxx 号" maxlength="128" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="公安备案链接" prop="psbLink">
              <el-input v-model="form.psbLink" placeholder="https://..." maxlength="512" clearable />
            </el-form-item>
          </el-col>
        </el-row>
        <div class="form-tip">备案号与链接均填写时 C 端才会展示对应项；链接须为 http/https 格式。</div>
      </el-card>

      <br/>

      <!-- 商品设置 -->
      <el-card shadow="never" class="section-card">
        <div slot="header">商品设置</div>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="商品货币符">
              <span class="readonly-text">{{ form.currencySymbol || '¥' }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商品货币中文">
              <span class="readonly-text">{{ form.currencyNameCn || '元' }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商品编号前缀">
              <span class="readonly-text">{{ form.goodsSnPrefix || 'SN' }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否显示销量" prop="showSales">
              <el-radio-group v-model="form.showSales">
                <el-radio label="1">是</el-radio>
                <el-radio label="0">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <div class="form-tip">关闭「显示销量」后 C 端商品详情与列表不展示销量数字，热销排序仍按销量字段计算。</div>
      </el-card>

      <br/>

      <!-- 订单设置 -->
      <el-card shadow="never" class="section-card">
        <div slot="header">订单设置</div>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="自动确认收货" prop="autoConfirmDays">
              <el-input-number
                v-model="form.autoConfirmDays"
                :min="1"
                :max="90"
                :precision="0"
                controls-position="right"
              />
              <span class="form-tip-inline">天（已发货后，自然日）</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="买家申请售后限制" prop="aftersaleLimitDays">
              <el-input-number
                v-model="form.aftersaleLimitDays"
                :min="1"
                :max="365"
                :precision="0"
                controls-position="right"
              />
              <span class="form-tip-inline">天（自确认收货起）</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="已支付订单可取消">
              <span class="readonly-text">{{ formatReadonlyBool(form.paidOrderCancelable) }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="已发货订单可取消发货">
              <span class="readonly-text">{{ formatReadonlyBool(form.shippedOrderCancelable) }}</span>
            </el-form-item>
          </el-col>
        </el-row>
        <div class="form-tip">自动确认收货与《订单管理》完成规则一致；在途已发货订单保存后按新天数重新判定。</div>
      </el-card>

      <br/>

      <!-- 会员默认头像 -->
      <el-card shadow="never" class="section-card">
        <div slot="header">会员默认头像</div>
        <el-form-item label="移动端默认头像" prop="defaultAvatar">
          <image-upload
            v-model="form.defaultAvatar"
            :limit="1"
            :file-size="5"
            :file-type="['png', 'jpg', 'jpeg']"
          />
        </el-form-item>
        <div v-if="form.defaultAvatar" class="avatar-preview">
          <span class="preview-label">预览：</span>
          <image-preview :src="form.defaultAvatar" :width="80" :height="80" />
        </div>
        <div class="form-tip">新注册或未上传头像的会员将展示此图片；已有自定义头像的会员不受影响。</div>
      </el-card>

      <br/>

      <!-- 操作按钮 -->
      <el-card shadow="never" class="section-card">
        <el-form-item label-width="0">
          <el-button type="primary" @click="submitForm" v-hasPermi="['agri:mall:setting:edit']">保 存</el-button>
          <el-button @click="loadConfig">重 置</el-button>
        </el-form-item>
      </el-card>
    </el-form>
  </div>
</template>

<script>
import { getMallSetting, saveMallSetting } from "@/api/agri/mall/setting"
import { validURL } from "@/utils/validate"

export default {
  name: "AgriMallSetting",
  data() {
    // 备案链接：非空时须为合法 http/https URL
    const validateFilingLink = (rule, value, callback) => {
      if (!value || !String(value).trim()) {
        callback()
        return
      }
      if (!validURL(value)) {
        callback(new Error("备案链接格式不正确，须为 http 或 https 地址"))
        return
      }
      callback()
    }
    return {
      // 页面加载遮罩
      loading: true,
      // 表单数据
      form: {
        icpNo: "",
        icpLink: "",
        psbNo: "",
        psbLink: "",
        currencySymbol: "¥",
        currencyNameCn: "元",
        goodsSnPrefix: "SN",
        showSales: "1",
        autoConfirmDays: 7,
        aftersaleLimitDays: 7,
        paidOrderCancelable: false,
        shippedOrderCancelable: false,
        defaultAvatar: ""
      },
      // 表单校验规则
      rules: {
        icpLink: [{ validator: validateFilingLink, trigger: "blur" }],
        psbLink: [{ validator: validateFilingLink, trigger: "blur" }],
        showSales: [{ required: true, message: "请选择是否显示销量", trigger: "change" }],
        autoConfirmDays: [{ required: true, message: "请填写自动确认收货天数", trigger: "blur" }],
        aftersaleLimitDays: [{ required: true, message: "请填写售后申请限制天数", trigger: "blur" }],
        defaultAvatar: [{ required: true, message: "请上传会员默认头像", trigger: "change" }]
      }
    }
  },
  created() {
    this.loadConfig()
  },
  methods: {
    /** 加载全平台商城设置 */
    loadConfig() {
      this.loading = true
      getMallSetting().then(response => {
        const data = response.data || {}
        this.form = {
          icpNo: data.icpNo || "",
          icpLink: data.icpLink || "",
          psbNo: data.psbNo || "",
          psbLink: data.psbLink || "",
          currencySymbol: data.currencySymbol || "¥",
          currencyNameCn: data.currencyNameCn || "元",
          goodsSnPrefix: data.goodsSnPrefix || "SN",
          showSales: data.showSales != null ? String(data.showSales) : "1",
          autoConfirmDays: data.autoConfirmDays != null ? data.autoConfirmDays : 7,
          aftersaleLimitDays: data.aftersaleLimitDays != null ? data.aftersaleLimitDays : 7,
          paidOrderCancelable: data.paidOrderCancelable === true,
          shippedOrderCancelable: data.shippedOrderCancelable === true,
          defaultAvatar: data.defaultAvatar || ""
        }
        this.loading = false
        this.$nextTick(() => {
          if (this.$refs.form) {
            this.$refs.form.clearValidate()
          }
        })
      }).catch(() => {
        this.loading = false
      })
    },
    /** 只读布尔展示为「是/否」 */
    formatReadonlyBool(val) {
      return val ? "是" : "否"
    },
    /** 保存商城设置（仅提交可编辑字段） */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (!valid) {
          return
        }
        const payload = {
          icpNo: this.form.icpNo,
          icpLink: this.form.icpLink,
          psbNo: this.form.psbNo,
          psbLink: this.form.psbLink,
          showSales: this.form.showSales,
          autoConfirmDays: this.form.autoConfirmDays,
          aftersaleLimitDays: this.form.aftersaleLimitDays,
          defaultAvatar: this.form.defaultAvatar
        }
        saveMallSetting(payload).then(response => {
          this.$modal.msgSuccess(response.msg || "保存成功")
          this.loadConfig()
        })
      })
    }
  }
}
</script>

<style scoped>
.card-header {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 12px;
}
.header-tip {
  color: #909399;
  font-size: 13px;
  font-weight: normal;
}
.page-desc {
  margin: 0;
  color: #606266;
  font-size: 13px;
  line-height: 1.6;
}
.section-card {
  margin-bottom: 0;
}
.readonly-text {
  color: #606266;
}
.form-tip {
  color: #909399;
  font-size: 12px;
  line-height: 1.5;
  margin-top: 4px;
}
.form-tip-inline {
  color: #909399;
  font-size: 12px;
  margin-left: 8px;
}
.avatar-preview {
  display: flex;
  align-items: center;
  margin-left: 180px;
  margin-top: -8px;
  margin-bottom: 8px;
}
.preview-label {
  color: #606266;
  font-size: 13px;
  margin-right: 8px;
}
</style>
