<template>
  <div class="app-container">
    <!-- 检索区 -->
    <el-card shadow="never" class="search-card">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="80px">
        <el-form-item label="关键词" prop="keyword">
          <el-input v-model="queryParams.keyword" placeholder="店铺/商户/经营账号" clearable style="width: 220px" @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item label="店铺状态" prop="shopStatus">
          <el-select v-model="queryParams.shopStatus" placeholder="全部" clearable style="width: 120px">
            <el-option label="开业" value="0" />
            <el-option label="停业" value="1" />
          </el-select>
        </el-form-item>
        <el-form-item label="商户名称" prop="merchantName">
          <el-input v-model="queryParams.merchantName" placeholder="商户名称" clearable style="width: 160px" @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <br/>

    <!-- 列表区 -->
    <el-card shadow="never" class="table-card">
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['agri:shop:add']">添加店铺</el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <el-table border v-loading="loading" :data="shopList">
        <el-table-column label="店铺名称" align="center" prop="shopName" min-width="140" :show-overflow-tooltip="true" />
        <el-table-column label="店铺头像" align="center" width="90">
          <template slot-scope="scope">
            <image-preview :src="scope.row.shopAvatar" :width="50" :height="50" />
          </template>
        </el-table-column>
        <el-table-column label="商户名称" align="center" prop="merchantName" min-width="140" :show-overflow-tooltip="true" />
        <el-table-column label="店铺状态" align="center" prop="shopStatus" width="90">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.shopStatus === '0'" type="success" size="small">开业</el-tag>
            <el-tag v-else type="info" size="small">停业</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="经营账号" align="center" min-width="160">
          <template slot-scope="scope">
            <span>{{ scope.row.accountAdminName || '—' }} / {{ scope.row.accountLoginName || '—' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="220" fixed="right">
          <template slot-scope="scope">
            <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['agri:shop:edit']">编辑</el-button>
            <el-button size="mini" type="text" icon="el-icon-user" @click="handleAccount(scope.row)" v-hasPermi="['agri:shop:account']">账号管理</el-button>
            <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['agri:shop:remove']">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />
    </el-card>

    <!-- 添加/编辑店铺弹窗 -->
    <el-dialog :title="title" :visible.sync="open" width="640px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="店铺名称" prop="shopName">
          <el-input v-model="form.shopName" placeholder="请输入店铺名称" maxlength="128" />
        </el-form-item>
        <el-form-item label="店铺头像" prop="shopAvatar">
          <image-upload v-model="form.shopAvatar" :limit="1" :file-size="5" :file-type="['png', 'jpg', 'jpeg']" />
        </el-form-item>
        <el-form-item label="商家电话" prop="shopPhone">
          <el-input v-model="form.shopPhone" placeholder="选填，手机或固话" maxlength="20" />
        </el-form-item>
        <el-form-item label="店铺描述" prop="shopDesc">
          <el-input v-model="form.shopDesc" type="textarea" :rows="3" maxlength="1000" show-word-limit placeholder="选填" />
        </el-form-item>
        <el-form-item v-if="!form.shopId" label="选择商户" prop="merchantId">
          <el-select v-model="form.merchantId" filterable placeholder="请选择商户" style="width: 100%" @change="handleMerchantChange">
            <el-option v-for="item in merchantOptions" :key="item.merchantId" :label="item.merchantName || item.unitName" :value="item.merchantId" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="!form.shopId && merchantAccountHint" label="经营账号">
          <span class="readonly-text">{{ merchantAccountHint }}</span>
          <div class="form-tip">经营账号由商户入驻时绑定，开店沿用该账号</div>
        </el-form-item>
        <el-form-item v-else-if="form.shopId" label="所属商户">
          <span class="readonly-text">{{ form.merchantName || '—' }}</span>
        </el-form-item>
        <el-form-item v-if="form.shopId" label="经营账号">
          <span class="readonly-text">{{ form.accountAdminName || '—' }} / {{ form.accountLoginName || '—' }}</span>
          <div class="form-tip">如需修改请使用「账号管理」</div>
        </el-form-item>
        <el-form-item v-if="!form.shopId" label="店铺状态" prop="shopStatus">
          <el-radio-group v-model="form.shopStatus">
            <el-radio label="0">开业</el-radio>
            <el-radio label="1">停业</el-radio>
          </el-radio-group>
          <div class="form-tip">未选择时默认开业</div>
        </el-form-item>
        <el-form-item v-if="form.shopId" label="店铺状态" prop="shopStatus">
          <el-radio-group v-model="form.shopStatus">
            <el-radio label="0">开业</el-radio>
            <el-radio label="1">停业</el-radio>
          </el-radio-group>
          <div v-if="form.shopStatus === '1'" class="form-tip">停业后用户端将无法下单</div>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 店铺账号管理弹窗 -->
    <el-dialog title="店铺账号管理" :visible.sync="accountOpen" width="560px" append-to-body>
      <el-form ref="accountForm" :model="accountForm" :rules="accountRules" label-width="100px">
        <el-alert v-if="accountForm.shops && accountForm.shops.length" type="info" :closable="false" class="mb12">
          修改后将同步至该商户下全部店铺（共 {{ accountForm.shops.length }} 家）
        </el-alert>
        <div v-if="accountForm.shops && accountForm.shops.length" class="shop-tags mb12">
          <el-tag v-for="item in accountForm.shops" :key="item.shopId" size="small" class="shop-tag" :type="item.shopStatus === '0' ? 'success' : 'info'">
            {{ item.shopName }}
          </el-tag>
        </div>
        <el-form-item label="登录名" prop="loginNameRaw">
          <el-input
            v-model="accountForm.loginNameRaw"
            :placeholder="accountForm.loginNameMasked ? ('当前 ' + accountForm.loginNameMasked + '，修改请填完整手机号') : '11位手机号'"
            maxlength="11"
          />
          <div class="form-tip">登录名须为 11 位手机号，修改后将同步至该商户下全部店铺</div>
        </el-form-item>
        <el-form-item label="管理员姓名" prop="adminName">
          <el-input v-model="accountForm.adminName" placeholder="管理员姓名" maxlength="64" />
        </el-form-item>
        <el-form-item label="重置密码" prop="password">
          <el-input v-model="accountForm.password" type="password" placeholder="留空则不修改" maxlength="20" show-password />
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button type="primary" @click="submitAccount">保 存</el-button>
        <el-button @click="accountOpen = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listShop, getShop, addShop, updateShop, delShop, deleteShopCheck, getShopAccount, updateShopAccount } from "@/api/agri/shop"
import { selectMerchantList, openShopCheck } from "@/api/agri/merchant"

export default {
  name: "AgriShop",
  data() {
    /** 商家电话：添加/编辑均为选填；有值时校验格式（v1.3.6） */
    const validateShopPhone = (rule, value, callback) => {
      if (!value || !String(value).trim()) {
        callback()
        return
      }
      if (!/^[0-9\-+()\s]{5,20}$/.test(String(value).trim())) {
        callback(new Error("请输入正确的电话格式"))
        return
      }
      callback()
    }
    /** 经营账号登录名：11 位手机号（v1.3） */
    const validateLoginName = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请输入登录名"))
        return
      }
      if (!/^1[3-9]\d{9}$/.test(value)) {
        callback(new Error("登录名须为11位手机号"))
        return
      }
      callback()
    }
    return {
      loading: true,
      showSearch: true,
      total: 0,
      shopList: [],
      title: "",
      open: false,
      accountOpen: false,
      merchantOptions: [],
      merchantAccountHint: null,
      merchantAccountOk: false,
      currentMerchantId: null,
      originalShopStatus: "0",
      originalLoginName: "",
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        keyword: undefined,
        shopStatus: undefined,
        merchantName: undefined
      },
      form: {},
      accountForm: {},
      rules: {
        shopName: [{ required: true, message: "请输入店铺名称", trigger: "blur" }],
        shopAvatar: [{ required: true, message: "请上传店铺头像", trigger: "change" }],
        shopPhone: [{ validator: validateShopPhone, trigger: "blur" }],
        merchantId: [{ required: true, message: "请选择商户", trigger: "change" }]
      },
      accountRules: {
        loginNameRaw: [
          { required: true, message: "请输入登录名", trigger: "blur" },
          { validator: validateLoginName, trigger: "blur" }
        ],
        adminName: [{ required: true, message: "请输入管理员姓名", trigger: "blur" }]
      }
    }
  },
  created() {
    // 支持从商户详情跳转带入商户名称筛选
    if (this.$route.query.merchantName) {
      this.queryParams.merchantName = this.$route.query.merchantName
    }
    this.getList()
    this.loadMerchantOptions()
  },
  methods: {
    /** 查询店铺列表 */
    getList() {
      this.loading = true
      listShop(this.queryParams).then(response => {
        this.shopList = response.rows || []
        this.total = response.total || 0
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    /** 加载可选商户 */
    loadMerchantOptions() {
      selectMerchantList().then(response => {
        this.merchantOptions = response.data || response.rows || []
      }).catch(() => {})
    },
    /** 重置表单 */
    reset() {
      this.form = {
        shopId: undefined,
        shopName: undefined,
        shopAvatar: undefined,
        shopPhone: undefined,
        shopDesc: undefined,
        shopStatus: "0",
        merchantId: undefined,
        merchantName: undefined,
        accountAdminName: undefined,
        accountLoginName: undefined
      }
      this.merchantAccountHint = null
      this.merchantAccountOk = false
      this.resetForm("form")
    },
    /** 取消弹窗 */
    cancel() {
      this.open = false
      this.reset()
    },
    /** 搜索 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置检索 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    /** 打开添加 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加店铺"
    },
    /** 打开编辑 */
    handleUpdate(row) {
      this.reset()
      getShop(row.shopId).then(response => {
        this.form = response.data
        this.originalShopStatus = this.form.shopStatus || "0"
        this.open = true
        this.title = "编辑店铺"
      })
    },
    /** 选择商户后校验可开店并展示已有经营账号 */
    handleMerchantChange(merchantId) {
      this.merchantAccountHint = null
      this.merchantAccountOk = false
      if (!merchantId) {
        return
      }
      openShopCheck(merchantId).then(response => {
        const check = response.data || {}
        if (!check.allowed) {
          this.$modal.msgWarning(check.reason || "请先完善该商户的经营与结算信息")
          this.form.merchantId = undefined
          return
        }
        getShopAccount(merchantId).then(res => {
          const data = res.data || {}
          if (!data.loginName && !data.adminName) {
            this.$modal.msgWarning("该商户尚未配置经营账号，请先在商户管理中完成入驻绑定")
            this.form.merchantId = undefined
            return
          }
          this.merchantAccountHint = (data.adminName || "—") + " / " + (data.loginName || "—")
          this.merchantAccountOk = true
        }).catch(() => {
          this.form.merchantId = undefined
        })
      }).catch(() => {
        this.form.merchantId = undefined
      })
    },
    /** 构建添加店铺请求体（不含经营账号字段） */
    buildAddPayload() {
      const payload = {
        shopName: this.form.shopName,
        shopAvatar: this.form.shopAvatar,
        merchantId: this.form.merchantId
      }
      if (this.form.shopPhone) {
        payload.shopPhone = this.form.shopPhone
      }
      if (this.form.shopDesc) {
        payload.shopDesc = this.form.shopDesc
      }
      if (this.form.shopStatus && this.form.shopStatus !== "0") {
        payload.shopStatus = this.form.shopStatus
      }
      return payload
    },
    /** 构建编辑店铺请求体（不含 merchantId、经营账号） */
    buildUpdatePayload(confirm) {
      const payload = {
        shopId: this.form.shopId,
        shopName: this.form.shopName,
        shopAvatar: this.form.shopAvatar,
        shopDesc: this.form.shopDesc,
        shopStatus: this.form.shopStatus
      }
      if (this.form.shopPhone && String(this.form.shopPhone).trim()) {
        payload.shopPhone = this.form.shopPhone.trim()
      }
      // 开业→停业：首次提交 confirm:false，由后端返回 needConfirm
      if (this.originalShopStatus === "0" && this.form.shopStatus === "1") {
        payload.confirm = confirm === true
      }
      return payload
    },
    /** 提交店铺表单 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (!valid) {
          return
        }
        if (this.form.shopId) {
          this.doUpdateShop()
        } else {
          if (!this.merchantAccountOk) {
            this.$modal.msgWarning("请先选择已绑定经营账号的商户")
            return
          }
          addShop(this.buildAddPayload()).then(() => {
            this.$modal.msgSuccess("添加成功")
            this.open = false
            this.getList()
          })
        }
      })
    },
    /** 编辑店铺（含停业二次确认 S12） */
    doUpdateShop(confirm) {
      updateShop(this.buildUpdatePayload(confirm)).then(response => {
        if (response.data && response.data.needConfirm) {
          this.$modal.confirm(response.data.confirmMessage || "停业后用户端将无法下单，是否继续？").then(() => {
            this.doUpdateShop(true)
          }).catch(() => {})
          return
        }
        this.$modal.msgSuccess("修改成功")
        this.open = false
        this.getList()
      })
    },
    /** 打开账号管理 */
    handleAccount(row) {
      this.currentMerchantId = row.merchantId
      getShopAccount(row.merchantId).then(response => {
        const data = response.data || {}
        const loginRaw = data.loginNameRaw || ""
        this.originalLoginName = loginRaw
        this.accountForm = {
          loginNameRaw: loginRaw,
          loginNameMasked: data.loginName || "",
          adminName: data.adminName,
          password: undefined,
          shops: data.shops || []
        }
        this.accountOpen = true
      })
    },
    /** 保存账号（改登录名需 confirm） */
    submitAccount(confirm) {
      this.$refs["accountForm"].validate(valid => {
        if (!valid) {
          return
        }
        const payload = {
          loginName: this.accountForm.loginNameRaw,
          adminName: this.accountForm.adminName,
          password: this.accountForm.password || null
        }
        // 改登录名时走两步 confirm（v1.3）；未改登录名则不传 confirm
        if (this.accountForm.loginNameRaw !== this.originalLoginName) {
          payload.confirm = confirm === true
        }
        updateShopAccount(this.currentMerchantId, payload).then(response => {
          if (response.data && response.data.needConfirm) {
            this.$modal.confirm(response.data.confirmMessage || "将同步至该商户下全部店铺，是否继续？").then(() => {
              this.submitAccount(true)
            }).catch(() => {})
            return
          }
          this.$modal.msgSuccess("保存成功")
          this.accountOpen = false
          this.getList()
        })
      })
    },
    /** 删除店铺（先预检再确认） */
    handleDelete(row) {
      deleteShopCheck(row.shopId).then(response => {
        const data = response.data || {}
        if (data.canDelete === false) {
          const reasons = (data.reasons || []).join("；")
          this.$modal.msgWarning(reasons || "当前店铺不满足删除条件")
          return
        }
        this.$modal.confirm("删除后不可恢复，是否继续？").then(() => {
          return delShop(row.shopId)
        }).then(() => {
          this.$modal.msgSuccess("删除成功")
          this.getList()
        }).catch(() => {})
      }).catch(() => {})
    }
  }
}
</script>

<style scoped>
.search-card {
  margin-bottom: 0;
}
.form-tip {
  color: #909399;
  font-size: 12px;
  margin-top: 4px;
}
.readonly-text {
  color: #606266;
}
.mb12 {
  margin-bottom: 12px;
}
.shop-tags {
  padding-left: 100px;
}
.shop-tag {
  margin-right: 8px;
  margin-bottom: 4px;
}
</style>
