<template>
  <div class="app-container">
    <el-row :gutter="20"
      class="row">
      <!--商品分类-->
      <category-tree :options="tagsOptions"
        :defaultProps="defaultProps"
        :nodeKey="nodeKey"
        placeholder="搜索商品集合标签"
        v-model="queryParams.prdTagId"
        @search="handleQuery"
        :colSpan="14"
        :rowGap="true"
        showEditDel
        @flodEdit="handleFlodEdit"
        @flodDel="handleFlodDel"
        :loading="flodLoading"
        :showIcon="true"
        :isPagination="true"
        :total="tagTotal"
        @pageChange="getSeriesGoodsTagList">
        <template #buttons>
          <el-button type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['gen:info:add']">新增</el-button>
        </template>
      </category-tree>
      <el-col :span="10"
        :xs="24"
        class="right_col">
        <el-table v-loading="loading"
          :data="prdList">
          <el-table-column label="商品编码"
            prop="prdCode" />
          <el-table-column label="商品名称"
            prop="prdName" />
          <el-table-column label="系列名称"
            prop="series" />
        </el-table>
        <!-- 添加或修改商品-标签详情对话框 -->
        <el-dialog :title="title"
          v-model:visible="open"
          append-to-body>
          <el-form ref="formRef"
            :model="form"
            :rules="rules"
            label-width="120px">
            <el-form-item label="标签名称"
              prop="prdTagName">
              <el-input v-model="form.prdTagName"
                placeholder="请输入标签名称" />
            </el-form-item>
            <el-form-item label="系列和商品"
              prop="seriesPrdMap">
              <el-cascader v-model="form.seriesPrdMap"
                v-if="open"
                :options="seriesPrdOptions"
                :props="props"
                collapse-tags
                clearable
                filterable
                popper-class="my_popper"></el-cascader>
            </el-form-item>
          </el-form>
          <div slot="footer"
            class="dialog-footer">
            <el-button type="primary"
              @click="submitForm">确 定</el-button>
            <el-button @click="cancel">取 消</el-button>
          </div>
        </el-dialog>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
// import { listInfo, getInfo, delInfo, addInfo, updateInfo } from "@/api/gen/info";
import { getSeriesListAPI, getProductListAPI, createSeriesGoodsTagAPI, getSeriesGoodsTagListAPI, getPrdTagDetailAPI, deleteSeriesGoodsTagAPI } from '@/api';

const { proxy } = getCurrentInstance();

// 左侧-商品集合标签相关数据
const formRef = ref(null)
const tagsOptions = ref([]);
const defaultProps = reactive({
  children: 'children',
  label: 'prdTagName'
});
const nodeKey = 'prdTagId';
// 查询参数
const queryParams = ref({
  prdTagId: null
});
// 右侧-商品列表
const prdList = ref([]);
// 左侧-商品集合标签-刷新状态
const flodLoading = ref(false);
// 弹出层标题
const title = ref('');
// 是否显示弹出层
const open = ref(false);
// 表格数据遮罩层
const loading = ref(true);
// 商品集合标签-表单参数
const form = ref({});
// 商品集合标签-表单校验
const rules = reactive({
  prdTagName: [
    { required: true, message: "标签名称不能为空", trigger: "blur" },
    { min: 1, max: 7, message: '长度在 1 到 7 个字符', trigger: 'blur' }
  ],
  seriesPrdMap: [
    { required: true, message: "系列和商品不能为空", trigger: "blur" }
  ]
});
// 左侧商品标签总数
const tagTotal = ref(0);

// 级联选择器配置
const props = reactive({
  multiple: true,
  lazy: true,
  async lazyLoad(node, resolve) {
    const { level } = node;
    if (node.children?.length > 0) {
      return resolve();
    }
    // 隐藏第二级列叶子节点没子菜单点击还加载的效果
    if (level === 2) {
      node.loading = false;
      return resolve([]);
    }
    const { data: { total } } = await getProductListAPI({ seriesId: node.value });
    const { data: { rows } } = await getProductListAPI({ seriesId: node.value, pageNum: 1, pageSize: total });
    const nodes = rows.map(item => ({
      value: item.prdCode,
      label: item.prdName,
      leaf: true
    }));
    // 通过调用resolve将子节点数据返回，通知组件数据加载完成
    resolve(nodes);
  }
});
// 系列和商品-级联数据
const seriesPrdOptions = ref([]);

// 获取系列数据列表
const getSeriesList = async () => {
  const response = await getSeriesListAPI();
  seriesPrdOptions.value = response.data.map(obj => {
    return {
      value: obj.seriesId,
      label: obj.seriesName
    };
  });
};

// 获取商品-标签集合列表
const getSeriesGoodsTagList = async (queryParams = { pageNum: 1, pageSize: 10 }) => {
  const { data: { total, rows } } = await getSeriesGoodsTagListAPI({
    ...queryParams,
    tagNameLike: queryParams.searchKey
  });
  tagTotal.value = total;
  tagsOptions.value = rows;
  // 获取商品-标签指定第一个详情
  queryParams.prdTagId = rows[0]?.prdTagId;
  getTagDetailsList();
};

/** 查询商品-标签详情列表 */
const getTagDetailsList = async () => {
  loading.value = true;
  const response = await getPrdTagDetailAPI({
    prdTagId: queryParams.value.prdTagId
  });
  prdList.value = response.data;
  loading.value = false;
};
const handleFlodEdit = async (row) => {
  reset();
  // 获取标签详情数据
  const res = await getPrdTagDetailAPI({
    prdTagId: row.prdTagId
  })
  // ========准备级联选择器数据==========
  // 准备系列 id 数组
  const seriesIds = [...new Set(res.data.map(obj => obj.seriesId))]
  // 把需要的系列下属的商品列表也查询出来
  seriesPrdOptions.value.map(async obj => {
    // 当前系列是否需要查询
    if (!seriesIds.includes(obj.value)) {
      // 删除之前的 children 字段
      delete obj.children
    } else {
      // 给系列下属物品列表全都请求回来-这步是显示列表还不是回显勾选
      const { data: { total } } = await getProductListAPI({ seriesId: obj.value })
      const { data: { rows } } = await getProductListAPI({ seriesId: obj.value, pageNum: 1, pageSize: total })
      const childrenRows = rows.map(item => ({
        value: item.prdCode,
        label: item.prdName,
        leaf: true
      }));
      obj.children = childrenRows
    }
  })
  open.value = true;
  title.value = "修改商品-标签详情";
  // ===== 回显数据 =====
  nextTick(() => {
    form.value.prdTagId = row.prdTagId
    form.value.prdTagName = row.prdTagName
    // 回显给数据绑定 v-model 的值
    form.value.seriesPrdMap = res.data.map(obj => {
      return [obj.seriesId, obj.prdCode]
    })
    form.value.seriesPrdMap = seriesPrdMap
  })
}
// 商品集合标签点击-删除
const handleFlodDel = async (row) => {
  proxy.$modal.confirm('确认删除商品标签"' + row.prdTagName + '"？').then(async () => {
    flodLoading.value = true
    await deleteSeriesGoodsTagAPI(row.prdTagId)
    await getSeriesGoodsTagList()
    proxy.$modal.msgSuccess("删除成功");
    flodLoading.value = false
  })
}
// 取消按钮
const cancel = () => {
  open.value = false;
  reset();
}
// 表单重置
const reset = () => {
  form.value = {
    tagId: null,
    prdTagName: null,
    seriesPrdMap: null
  };
  resetForm("form");
}
/** 商品集合标签点击-搜索右侧商品列表 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getTagDetailsList();
}
/** 新增按钮操作 */
const handleAdd = () => {
  form.prdTagId && reset();
  open.value = true;
  title.value = "添加商品-标签详情";
}
/** 提交按钮 */
const submitForm = () => {
  formRef.value.validate(valid => {
    if (valid) {
      // 数据结构要处理成后端需要的
      const uploadData = {
        tagName: form.value.prdTagName,
        prdCodes: []
      }
      form.value.seriesPrdMap.map(arr => {
        uploadData.prdCodes.push(arr[1])
      })

      if (form.value.prdTagId != null) {
        // 后台没有修改接口，先删除后新增
        deleteSeriesGoodsTagAPI(form.value.prdTagId).then(response => {
          createSeriesGoodsTagAPI(uploadData).then(response => {
            proxy.$modal.msgSuccess("修改成功");
            open.value = false;
            getSeriesGoodsTagList();
          });
        });
      } else {
        createSeriesGoodsTagAPI(uploadData).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getSeriesGoodsTagList();
          reset();
        });
      }
    }
  });
}
getSeriesList();
getSeriesGoodsTagList()

</script>

<style scoped
  lang="scss">
  ::v-deep .row {
    height: 100%;
    display: flex;

    .right_col {
      flex: 1;
      overflow: scroll;

      &::-webkit-scrollbar {
        height: 0;
      }
    }
  }


</style>
<style lang="scss">
.my_popper {
  .el-scrollbar__wrap {
    height: 400px !important;
  }
}
</style>
