<template>
  <div class="app-container">
    <el-card shadow="never" class="setting-card" v-loading="loading">
      <div slot="header" class="card-header">
        <span class="card-title">发货信息设置</span>
      </div>

      <el-alert
        v-if="!hasSetting"
        title="请完善发货信息，便于买家在商品详情了解发货地（展示发货城市）。"
        type="info"
        :closable="false"
        show-icon
        class="tip-alert"
      />

      <el-form ref="form" :model="form" :rules="rules" label-width="130px" class="delivery-form">
        <el-form-item label="发货人" prop="shipperName">
          <el-input v-model="form.shipperName" placeholder="请输入发货人姓名" maxlength="64" show-word-limit style="max-width: 480px" />
        </el-form-item>
        <el-form-item label="发货人联系方式" prop="shipperMobile">
          <el-input v-model="form.shipperMobile" placeholder="请输入11位手机号" maxlength="11" style="max-width: 480px" />
        </el-form-item>
        <el-form-item label="发货地区" prop="shipRegionCascader">
          <el-cascader
            v-model="form.shipRegionCascader"
            :options="regionTree"
            :props="regionCascaderProps"
            clearable
            filterable
            placeholder="请选择省 / 市 / 区县"
            style="width: 480px"
            @change="handleShipRegionChange"
          />
        </el-form-item>
        <el-form-item label="发货详细地址" prop="detailAddress">
          <el-input
            v-model="form.detailAddress"
            type="textarea"
            :rows="3"
            placeholder="请输入街道、门牌号等详细地址"
            maxlength="256"
            show-word-limit
            style="max-width: 640px"
          />
        </el-form-item>
        <el-form-item v-if="updateTime" label="最近更新">
          <span class="update-time">{{ parseTime(updateTime) }}</span>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm" v-hasPermi="['agri:seller:delivery:edit']">保 存</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { getSellerDeliverySetting, saveSellerDeliverySetting } from "@/api/agri/seller/delivery"
import { getSellerContext } from "@/api/agri/seller/context"
import { setSellerShopContext } from "@/utils/sellerShop"
import regionCascaderMixin from "@/mixins/regionCascader"

export default {
  name: "AgriSellerDelivery",
  mixins: [regionCascaderMixin],
  data() {
    const validateMobile = (rule, value, callback) => {
      const text = value ? String(value).trim() : ""
      if (!text) {
        callback(new Error("请填写发货人联系方式"))
        return
      }
      if (!/^1[3-9]\d{9}$/.test(text)) {
        callback(new Error("请填写正确的发货人联系方式"))
        return
      }
      callback()
    }
    const validateRegion = (rule, value, callback) => {
      if (!this.form.shipRegionCode) {
        callback(new Error("请选择完整的发货地区"))
        return
      }
      callback()
    }
    return {
      loading: false,
      hasSetting: false,
      updateTime: null,
      form: {
        shipperName: "",
        shipperMobile: "",
        shipRegionCascader: [],
        shipRegionCode: undefined,
        shipRegionName: undefined,
        detailAddress: ""
      },
      rules: {
        shipperName: [{ required: true, message: "请填写发货人", trigger: "blur" }],
        shipperMobile: [{ validator: validateMobile, trigger: "blur" }],
        shipRegionCascader: [{ validator: validateRegion, trigger: "change" }],
        detailAddress: [{ required: true, message: "请填写发货详细地址", trigger: "blur" }]
      }
    }
  },
  created() {
    this.initPage()
  },
  methods: {
    initPage() {
      this.loadShopContext().then(() => {
        this.loadSetting()
      }).catch(() => {
        this.loadSetting()
      })
    },
    loadShopContext() {
      return getSellerContext().then(response => {
        const data = response.data || {}
        if (data.shopId != null) {
          setSellerShopContext(data.shopId, data.shopName)
        }
      })
    },
    loadSetting() {
      this.loading = true
      Promise.all([this.loadRegionTree(), getSellerDeliverySetting()]).then(([, response]) => {
        const data = response.data
        this.applySettingData(data)
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    applySettingData(data) {
      if (!data || !data.settingId) {
        this.hasSetting = false
        this.updateTime = null
        this.resetFormData()
        return
      }
      this.hasSetting = true
      this.updateTime = data.updateTime
      this.form = {
        shipperName: data.shipperName || "",
        shipperMobile: data.shipperMobile || "",
        shipRegionCascader: [],
        shipRegionCode: data.region ? data.region.regionCode : undefined,
        shipRegionName: this.formatRegionName(data.region),
        detailAddress: data.detailAddress || ""
      }
      this.syncRegionCascaderFromForm([
        { codeKey: "shipRegionCode", cascaderKey: "shipRegionCascader" }
      ])
    },
    formatRegionName(region) {
      if (!region) {
        return undefined
      }
      const parts = [region.provinceName, region.cityName, region.districtName].filter(Boolean)
      return parts.length ? parts.join("/") : undefined
    },
    handleShipRegionChange(codes) {
      this.applyRegionSelection(codes, "ship")
      this.$refs.form && this.$refs.form.validateField("shipRegionCascader")
    },
    resetFormData() {
      this.form = {
        shipperName: "",
        shipperMobile: "",
        shipRegionCascader: [],
        shipRegionCode: undefined,
        shipRegionName: undefined,
        detailAddress: ""
      }
      this.resetForm("form")
    },
    submitForm() {
      this.$refs.form.validate(valid => {
        if (!valid) {
          return
        }
        const payload = {
          shipperName: (this.form.shipperName || "").trim(),
          shipperMobile: (this.form.shipperMobile || "").trim(),
          region: {
            regionCode: this.form.shipRegionCode
          },
          detailAddress: (this.form.detailAddress || "").trim()
        }
        saveSellerDeliverySetting(payload).then(() => {
          this.$modal.msgSuccess("保存成功")
          this.loadSetting()
        })
      })
    }
  }
}
</script>

<style scoped lang="scss">
.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.card-title {
  font-weight: 600;
  font-size: 15px;
}
.tip-alert {
  margin-bottom: 20px;
}
.delivery-form {
  max-width: 820px;
}
.update-time {
  color: #909399;
  font-size: 13px;
}
</style>
