<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.tmerclub.cloud.product.mapper.CategoryBrandMapper">
  <resultMap id="categoryBrandMap" type="com.tmerclub.cloud.product.model.CategoryBrand">
    <id column="id" property="id" />
    <result column="create_time" property="createTime"/>
    <result column="update_time" property="updateTime"/>
    <result column="brand_id" property="brandId"/>
    <result column="category_id" property="categoryId"/>
  </resultMap>
  <resultMap id="categoryVOMap" type="com.tmerclub.cloud.common.product.vo.CategoryVO">
    <id column="category_id" property="categoryId" />
    <result column="parent_id" property="parentId"/>
    <result column="path" property="path"/>
    <collection property="categoryLangList" ofType="com.tmerclub.cloud.common.product.vo.CategoryLangVO">
      <id column="lang" property="lang"/>
      <result column="name" property="name"/>
    </collection>
  </resultMap>
  <sql id="Vo_Column_List">
    `id`,`create_time`,`update_time`,`brand_id`,`category_id`
  </sql>
  <delete id="deleteByBrandId">
    delete from category_brand where brand_id in
    <foreach collection="brandIdList" item="brandId" separator="," open="(" close=")">
      #{brandId}
    </foreach>
  </delete>

  <insert id="saveBatch">
    <foreach collection="categoryBrandList" item="categoryBrand">
      insert into category_brand (`brand_id`,`category_id`)
      values (#{categoryBrand.brandId},#{categoryBrand.categoryId});
    </foreach>
  </insert>

  <select id="getCategoryIdsByBrandId" resultType="java.lang.Long">
    SELECT category_id FROM category_brand WHERE brand_id = #{brandId}
  </select>

  <delete id="deleteByBrandIdAndCategoryIds">
    DELETE FROM category_brand
    WHERE brand_id = #{brandId} AND category_id IN
    <foreach collection="categoryIds" item="categoryId" separator="," open="(" close=")">
      #{categoryId}
    </foreach>
  </delete>

  <select id="getCategoryByBrandId" resultMap="categoryVOMap">
    SELECT cl.lang,cl.name,c.category_id,c.parent_id,c.path
    FROM category_brand cb
    JOIN category c ON c.category_id = cb.category_id
    JOIN category_lang cl ON cl.category_id = cb.category_id
    WHERE brand_id = #{brandId}
  </select>
  <select id="countByBrandIdAndCategoryId" resultType="java.lang.Integer">
    SELECT COUNT(*) FROM category_brand
    <where>
      <if test="brandId != null and brandId != ''">
        AND brand_id = #{brandId}
      </if>
      <if test="categoryId != null and categoryId != ''">
        AND category_id = #{categoryId}
      </if>
    </where>
  </select>
</mapper>
