<?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.ruoyi.system.mapper.grid.GridGroupLandExtMapper">
    <resultMap id="BaseResultMap" type="com.ruoyi.system.domain.grid.ext.GridGroupLandExt">
        <id column="id" jdbcType="VARCHAR" property="id"/>
        <result column="group_id" jdbcType="VARCHAR" property="groupId"/>
        <result column="land_id" jdbcType="VARCHAR" property="landId"/>
        <result column="create_time" jdbcType="VARCHAR" property="createTime"/>
        <result column="landName" jdbcType="VARCHAR" property="landName"/>
    </resultMap>

    <select id="getByGroupId" resultMap="BaseResultMap">
        SELECT
        wgl.*,bw.wg_name as landName
        FROM
        grid_group_land wgl
        LEFT JOIN
        grid_region bw on bw.id = wgl.land_id
        <where>
            <if test="groupId != null and groupId != ''">
                and wgl.group_id = #{groupId}
            </if>
        </where>
    </select>

    <select id="getByGroupIds" resultMap="BaseResultMap">
        SELECT
        wgl.*,bw.wg_name as landName
        FROM
        grid_group_land wgl
        LEFT JOIN
        grid_region bw on bw.id = wgl.land_id
        <where>
            <if test="groupIds != null and groupIds.size()>0 ">
                and wgl.group_id in
                <foreach collection="groupIds" item="groupId" open="(" close=")" separator=",">
                    #{groupId}
                </foreach>
            </if>
        </where>
    </select>

    <select id="getRelatedCompanyList" resultType="java.util.Map">
        SELECT
        wcl.company_id as companyId,
        wc.company_name as companyName
        FROM
        grid_company_land wcl
        LEFT JOIN
        grid_company wc on wcl.company_id = wc.id
        <where>
            <if test="landIds != null and landIds.size()>0 ">
                and wcl.land_id in
                <foreach collection="landIds" item="landId" open="(" close=")" separator=",">
                    #{landId}
                </foreach>
            </if>
        </where>
        group by wcl.company_id
    </select>

    <select id="getPermuSortList" resultType="java.util.Map">
        SELECT wg.group_name as groupName,
        IFNULL(sum(bw.wg_area),0) as landAreaSum,
        IFNULL(sum(wcei.per_mu),0) as perMuSum
        FROM grid_group wg
        LEFT JOIN grid_group_land wgl on wgl.group_id = wg.id
        LEFT JOIN grid_region bw on bw.id = wgl.land_id
        LEFT JOIN
        (select * from grid_company_land where is_valid = '1') as wcl
        on wgl.land_id = wcl.land_id
        LEFT JOIN
        (select * from grid_company_economy_info where is_valid = '1' and year = #{year}) as wcei
        on wcl.company_id = wcei.company_id
        group by wg.id
        order by perMuSum desc
    </select>
</mapper>