<template>
  <div class="app-container">
    <el-row :gutter="20"
      class="client-fix-height container">
      <!-- 商品标签列表 -->
      <category-tree :options="tagsOptions"
        :defaultProps="defaultProps"
        :nodeKey="nodeKey"
        placeholder="搜索商品集合标签"
        v-model="queryParams.prdTagId"
        :colSpan="14"
        :rowGap="true"
        :customOptions="{
          showTool: true,
          showIcon: true,
          rowGap: 10,
          showPagination: true,
          total: tagTotal,
          loading: flodLoading
        }"
        @flodEdit="handleFlodEdit"
        @flodDel="handleFlodDel"
        @search="handleQuery"
        @listChange="getSeriesGoodsTagList">
        <template #buttons>
          <el-button type="primary"
            icon="Plus"
            @click="handleAdd">新增</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="商品名称"
            width="300"
            prop="prdName" />
          <el-table-column label="系列名称"
            prop="series" />
        </el-table>
      </el-col>
    </el-row>
    <!-- 添加/修改-商品标签 -->
    <el-dialog :title="title"
      v-model="visible"
      draggable>
      <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="visible"
            :options="seriesPrdOptions"
            :props="props"
            :show-all-levels="false"
            collapse-tags
            collapse-tags-tooltip
            clearable
            filterable></el-cascader>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button type="primary"
          @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { getSeriesListAPI, getProductListAPI, createSeriesGoodsTagAPI, getSeriesGoodsTagListAPI, getPrdTagDetailAPI, deleteSeriesGoodsTagAPI } from '@/api';

const { proxy } = getCurrentInstance();

const tagsOptions = ref([]); // 标签列表
const defaultProps = reactive({
  children: 'children',
  label: 'prdTagName'
});
const nodeKey = 'prdTagId';
const queryParams = reactive({ // 标签列表查询参数
  tagNameLike: null,
  pageNum: 1,
  pageSize: 10
});
const prdList = ref([]); // 右侧-商品列表
const flodLoading = ref(false); // 左侧-商品集合标签-刷新状态
const title = ref(''); // 弹出层标题
const visible = 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 { 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
    };
  });
};
getSeriesList();

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

  getTagDetailsList();
};
getSeriesGoodsTagList()

/** 商品标签-详情 */
const getTagDetailsList = async () => {
  loading.value = true;
  const response = await getPrdTagDetailAPI({
    prdTagId: queryParams.prdTagId
  });
  prdList.value = response.data;
  loading.value = false;
};

// 商品标签-编辑
const handleFlodEdit = async (row) => {
  // 获取标签详情数据
  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
    }
  })
  // ===== 回显数据 =====
  form.value.prdTagId = row.prdTagId
  form.value.prdTagName = row.prdTagName
  // 回显给数据绑定 v-model 的值
  form.value.seriesPrdMap = res.data.map(obj => {
    return [obj.seriesId, obj.prdCode]
  })
  visible.value = true;
  title.value = "修改商品-标签详情";
}
// 商品集合标签点击-删除
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 = () => {
  visible.value = false;
  reset();
}
// 表单重置
const reset = () => {
  form.value = {
    tagId: null,
    prdTagName: null,
    seriesPrdMap: null
  };
  proxy.$refs.formRef.resetForm();
}
/** 商品标签点击 */
const handleQuery = () => {
  queryParams.pageNum = 1;
  getTagDetailsList();
}
/** 新增商品标签 */
const handleAdd = () => {
  visible.value = true;
  nextTick(() => {
    form.value.prdTagId && reset();
    title.value = "添加商品-标签详情";
  })
}
/** 提交按钮 */
const submitForm = () => {
  proxy.$refs.formRef.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("修改成功");
            visible.value = false;
            getSeriesGoodsTagList();
          });
        });
      } else {
        createSeriesGoodsTagAPI(uploadData).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          visible.value = false;
          getSeriesGoodsTagList();
          reset();
        });
      }
    }
  });
}
</script>

<style scoped
  lang="scss">
  .app-container {
    .el-row {

      .right_col {
        flex: 1 !important;
        transition: all .5s;
        display: flex;
        flex-direction: column;
        height: 100%;

        .el-form-item {
          margin-bottom: 0;
        }

        .pagination {
          /* 没办法设置某个子元素单独在主轴排列方式，使用此方式可以 */
          margin-top: auto;
        }

        &.el-col-10 {
          width: 41.666666%;
          max-width: none;
        }

      }
    }

    ::v-deep(.el-dialog) {
      display: flex;
      flex-direction: column;

      .el-dialog__body {
        display: flex;
        flex-direction: column;

        .el-form {
          flex: 1;

          .el-cascader {
            width: 100%;
          }
        }
      }
    }

  }
</style>
