<template>
  <!-- 列表 -->
  <ContentWrap class="Content" style="min-height: 400px;border: unset;">
    <div style="position: relative;" class="search">
      <div style="text-align: right;">
        <el-button :icon="Operation" @click="showSearchMore" />
        <el-button v-hasPermi="['sale:merchant:create']" @click="showDialog('新增')" v-if="!mobile">
          <Icon class="mr-5px" icon="ep:plus" />
          新增
        </el-button>
      </div>
      <div class="searchMore" v-show="searchMoreShow">
        <el-form class="-mb-15px" :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">
          <el-form-item label="商户名称" prop="name">
            <el-input v-model="queryParams.name" placeholder="请输入商户名称" clearable @keyup.enter="handleQuery" />
          </el-form-item>
          <!-- <el-form-item label="商户状态" prop="status">
            <el-select v-model="queryParams.status" placeholder="请选择商户状态" clearable>
              <el-option label="请选择字典生成" value="" />
            </el-select>
          </el-form-item> -->
          <el-form-item label="负责人" prop="contact">
            <el-input v-model="queryParams.contact" placeholder="请输入负责人" clearable @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="所在地" prop="address">
            <el-input v-model="queryParams.address" placeholder="请输入所在地" clearable @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="负责人电话" prop="contactNumber">
            <el-input v-model="queryParams.contactNumber" placeholder="请输入负责人电话" clearable @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="官网" prop="website">
            <el-input v-model="queryParams.website" placeholder="请输入官网" clearable @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="维权电话" prop="complaintsHotline">
            <el-input v-model="queryParams.complaintsHotline" placeholder="请输入维权电话" clearable
              @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="客服电话" prop="customerServiceHotline">
            <el-input v-model="queryParams.customerServiceHotline" placeholder="请输入客服电话" clearable
              @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="queryParams.email" placeholder="请输入邮箱" clearable @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="服务到期时间" prop="expireTime">
            <el-date-picker v-model="queryParams.expireTime" style="width: auto;" value-format="YYYY-MM-DD HH:mm:ss"
              type="daterange" start-placeholder="开始日期" end-placeholder="结束日期"
              :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]" />
          </el-form-item>
          <el-form-item label="创建时间" prop="createTime">
            <el-date-picker v-model="queryParams.createTime" style="width: auto;" value-format="YYYY-MM-DD HH:mm:ss"
              type="daterange" start-placeholder="开始日期" end-placeholder="结束日期"
              :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]" />
          </el-form-item>
          <el-row>
            <el-col>
              <el-form-item>
                <el-button @click="hideSearchMore">
                  收起
                </el-button>
                <el-button @click="resetQuery">
                  重置
                </el-button>
                <el-button @click="handleQuery">
                  <Icon icon="ep:search" class="mr-5px" /> 搜索
                </el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </div>
    <el-row>
      <el-col v-for="(o, index) in list" class="card" :key="index" :span="7" :xl="7" :lg="7" :md="7" :sm="24" :xs="24"
        @mouseover="handleMouseOver(index)" @mouseout="handleMouseOut(index)">
        <el-card @click="showDialog('查看', o)">
          <div style="display: flex;justify-content: space-between;align-items: center;margin-bottom: 5px;">
            <p style="width: 100%;white-space: nowrap;text-overflow: ellipsis;overflow: hidden;font-size: 16px;color:#000"
              :title="o.name">{{ o.name }}
            </p>
            <div @click.stop="showDialog('编辑', o)" v-show="o.showSetting && !mobile" class="setting"
              v-hasPermi="['sale:merchant:update']">
              <el-icon size="20" color="rgb(220 223 231)">
                <Setting />
              </el-icon>
            </div>
          </div>
          <div style="display:flex;align-items: center;">
            <div
              style="width: 151px;height: 85px;margin-right:10px;border:1px solid rgb(220 223 231);border-radius: 5px;display: flex;align-items: center;justify-content: center;overflow: hidden;">
              <img :src="o.logoUrl" style="width: auto; height: auto;max-width: 100%;max-height: 100%;" />
            </div>
            <div style='line-height: 30px;width: calc(100% - 170px);'>
              <p>销量:{{o.salesVolume}}</p>
              <p>商品数量:{{o.skuCount}}</p>
              <p style="white-space: nowrap;text-overflow: ellipsis;width: 100%;overflow: hidden;" :title="o.address">{{
          getAreaPath(o.areaId) }}</p>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    <div v-if="list.length == 0">
      <p style="text-align: center;margin-top: 100px;">暂无商户</p>
    </div>
    <!-- 分页 -->
    <Pagination :total="total" v-model:page="queryParams.pageNo" v-model:limit="queryParams.pageSize"
      @pagination="getList" />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <!-- <MerchantForm ref="formRef" @success="getList" /> -->

  <MerchantTabs :tabs="tabs" :initialData="initialData" :buttonActions="buttonActions" ref="MerchantTabsRef"
    :isDetail="isDetail" :initialComponent="initialComponent" :dialogTitle="dialogTitle" :id="parentId"
    v-model="dialogVisible" :openType="openType" />
</template>

<script setup lang="ts">
import { MerchantApi, MerchantVO } from '@/api/system/sale/merchant'
import { Setting, Operation } from '@element-plus/icons-vue'
import MerchantTabs from './components/MerchantTabs.vue';
const { currentRoute, push } = useRouter() // 路由跳转
import * as AreaApi from '@/api/system/area'
import * as DiyTemplateApi from '@/api/mall/promotion/diy/template'

// 从路由中引入store中的app仓库
import { useAppStore } from '@/store/modules/app'
const appStore = useAppStore()
const mobile = computed(() => appStore.getMobile)


// 弹窗tabs数据
const tabs = ref([
  { name: 'BaseInfo', label: '基本信息', component: 'views/system/sale/merchant/components/MerchantBaseInfo' },
  { name: 'Store', label: '店铺', component: 'views/system/sale/merchant/components/MerchantStore' },
  { name: 'Product', label: '商品', component: 'views/system/sale/merchant/components/MerchantProduct' },
  { name: 'Order', label: '订单', component: 'views/system/sale/merchant/components/MerchantOrder' },
  { name: 'Service', label: '客服', component: 'views/system/sale/merchant/components/MerchantService' },
  { name: 'AfterSales', label: '售后', component: 'views/system/sale/merchant/components/MerchantAfterSales' },
  { name: 'Campaign', label: '活动', component: 'views/system/sale/merchant/components/MerchantCampaign' },
  { name: 'Points', label: '积分', component: 'views/system/sale/merchant/components/MerchantPoints' },
  { name: 'Advertisement', label: '广告', component: 'views/system/sale/merchant/components/MerchantAdvertisement' },
  { name: 'Highlights', label: '看点', component: 'views/system/sale/merchant/components/MerchantHighlights' },
  { name: 'Finance', label: '财务', component: 'views/system/sale/merchant/components/MerchantFinance' },
  { name: 'Employee', label: '人员', component: 'views/system/sale/merchant/components/MerchantEmployee' },
]);
const initialData = ref({
  id: undefined,
  name: undefined,
  status: 10,
  description: undefined,
  contact: undefined,
  address: undefined,
  contactNumber: undefined,
  website: undefined,
  complaintsHotline: undefined,
  createTime: undefined,
  customerServiceHotline: undefined,
  email: undefined,
  businessLicensePicture: undefined,
  expireTime: undefined,
  logoUrl: undefined,
  areaId: undefined
});

// 定义一个函数来重置 initialData
function resetInitialData() {
  // 使用 Object.keys 遍历对象的所有属性，并将它们设置为 undefined
  for (const key of Object.keys(initialData.value)) {
    initialData.value[key] = undefined;
  }
  initialData.value.status = 10;
}
provide('updateInitialData', initialData);



// 定义按钮和对应的方法
const buttonActions = ref([
  {
    name: '删除',
    action: deleteData,
    type: 'danger',
    // 如果是增加时不显示
    isAdd: false
  },
  {
    name: '保存',
    action: saveData,
    type: 'primary',
    isAdd: true
  },

  // 可以根据需要添加更多按钮和方法
]);
const MerchantTabsRef = ref();
//保存数据
async function saveData() {
  const valid = MerchantTabsRef.value.ComponentRef.validate()
  // 校验有没有logo
  if (!MerchantTabsRef.value.picUrl) {
    message.error('请上传logo')
    return
  }
  const validRes = await valid
  console.log(validRes)
  if (!validRes) {
    return
  }
  // 实现数据保存的逻辑
  // 提交请求
  try {
    const data = initialData.value as unknown as MerchantApi.MerchantVO
    if (initialData.value.id == undefined) {
      await MerchantApi.createMerchant(data).then((res) => {
        console.log('创建成功', res)
        console.log(initialData.value.name)
        DiyTemplateApi.createDiyTemplate({
          merId: res.merId,
          shopId: res.shopId,
          name: initialData.value.name
        })
      })
      message.success(t('common.createSuccess'))
      getList()
    } else {
      await MerchantApi.updateMerchant(data)
      message.success(t('common.updateSuccess'))
      getList()
    }
    dialogVisible.value = false
    // 发送操作成功的事件
  } finally {

  }
}
//删除
function deleteData() {
  // 调用删除
  handleDelete(initialData.value.id)
  // 关闭弹窗

}
const initialComponent = 'views/system/sale/merchant/components/MerchantBaseInfo';
const parentId = ref(0);
const dialogVisible = ref(false);
const dialogTitle = ref("")
const isDetail = ref(false);
const openType = ref("")
async function showDialog(opentype: string, row: object) {
  // 如果有row的话就是view或者edit
  openType.value = opentype;
  if (row != null) {
    // 如果row不为null则证明是有数据，即是说是编辑或者查看状态
    // 获取通过id查到数据再传给子组件
    initialData.value = await MerchantApi.getMerchant(row.id);
    // 如果是移动端，则进入移动端的页面
    if (mobile.value) {
      push({
        name: 'MobileDetail', query: {
          tabs: JSON.stringify(tabs.value),
          initialComponent: initialComponent.value,
          id: row.id,
          initialData: JSON.stringify(initialData.value),
          opentype: opentype
        }
      })
      return
    }
    if (opentype == "查看") {
      isDetail.value = true
    } else {
      isDetail.value = false
    }
    dialogTitle.value = opentype + "-" + row.name
    parentId.value = row.id;
  } else {
    isDetail.value = false
    dialogTitle.value = opentype
    parentId.value = 0;
    resetInitialData()
  }

  dialogVisible.value = true;
}
const searchMoreShow = ref(false)
// 鼠标移入显示变动图标
function handleMouseOver(index) {
  list.value[index].showSetting = true;
}
// 鼠标移出不显示图标
function handleMouseOut(index) {
  list.value[index].showSetting = false;
}
// 打开更多搜索条件
const showSearchMore = () => {
  searchMoreShow.value = !searchMoreShow.value
}
const hideSearchMore = () => {
  searchMoreShow.value = false
}


/** 商户列表 */
defineOptions({ name: 'Merchant' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<MerchantVO[]>([]) // 列表的数据
// 列表的总页数
const total = ref(0)
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  name: undefined,
  status: undefined,
  description: undefined,
  contact: undefined,
  address: undefined,
  contactNumber: undefined,
  website: undefined,
  complaintsHotline: undefined,
  customerServiceHotline: undefined,
  email: undefined,
  expireTime: [],
  createTime: []
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await MerchantApi.getMerchantPage(queryParams)
    data.list.forEach(obj => {
      obj.showSetting = false;
    });
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

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

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

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await MerchantApi.deleteMerchant(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
    dialogVisible.value = false
  } catch { }
}
/** 初始化 **/
const areaTree = ref([])
onMounted(async () => {
  // 获得地区树
  areaTree.value = await AreaApi.getAreaTree()
  getList()
  // 寻找ID对应的省市区路径

})
// 扁平化地区树，创建ID到节点信息的映射
const flattenTree = (tree) => {
  const map = new Map();
  const stack = [...tree.map(node => ({ ...node, parentId: null }))]; // 初始栈，根节点没有parentId
  while (stack.length > 0) {
    const node = stack.pop();
    map.set(node.id, { name: node.name, parentId: node.parentId });
    if (node.children) {
      stack.push(...node.children.map(child => ({ ...child, parentId: node.id }))); // 将子节点入栈，并记录其父节点ID
    }
  }

  return map;
};

// 通过映射表构建从根到目标ID的路径
const buildPathFromMap = (map, targetId) => {
  const path = [];
  let currentId = targetId;

  while (currentId !== null) {
    const node = map.get(currentId);
    if (!node) break; // 如果找不到节点，结束循环
    path.unshift(node.name); // 将当前节点名称加到路径开始
    currentId = node.parentId; // 向上回溯到父节点
  }

  return path;
};

// 主函数：给定一个目标ID，返回其路径
const getAreaPath = (targetId) => {
  const map = flattenTree(areaTree.value); // 扁平化地区树
  const path = buildPathFromMap(map, targetId); // 构建路径
  return path.join('/');
};



</script>


<style lang="scss" scoped>
@media screen and (max-width: 768px) {


  .card {
    margin: 10px 0 !important;
  }

  ::v-deep(.el-pagination__sizes),
  ::v-deep(.el-pagination__jump) {
    display: none;
  }


  .Content {
    min-height: 100vh !important;
  }

  ::v-deep(.el-tabs__item) {
    padding: 0 4px;
  }
}

::v-deep .el-form-item__label {
  width: auto !important;
}



::v-deep .el-card__body {
  padding: 0;
}

.searchMore {
  text-align: left;
  background: #f3f5f8;
  padding: 10px;
  position: absolute;
  width: calc(100% - 20px);
  z-index: 111;
  box-shadow: 0px 9px 6px rgba(0, 0, 0, 0.2);

  .el-row {
    text-align: right;
  }
}

.el-tabs {
  position: absolute;
  z-index: 111;
  top: 25px;
  left: 40px;
}

.card {
  font-size: 14px;
  margin: 10px;

  .el-card {
    padding: 15px;
    cursor: pointer;
    position: relative;

    :deep(.el-card__body) {
      padding: unset;
    }
  }

  .setting {
    width: 30px;
    top: 0px;
    right: 0px;
    position: absolute;
    height: 30px;
    line-height: 30px;
    text-align: center;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .setting:hover {
    background: #666
  }

  p,
  div {
    margin: unset;
    padding: unset;
  }
}
</style>