<?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.energy.manage.service.mappers.windrelation.WindRelationMapper">


    <sql id="BASE_COMPANY_SQL">
      wc.id AS id,
      wc.company_code AS companyCode,
      wc.company_name AS companyName,
	  wr.code_number as codeNumber,
	  wr.code_name as codeName,
	  wr.parent_code as parentCode,
      wc.state AS state,
      wc.province_id AS provinceId,
      wc.province_name as provinceName,
      wc.city_id as cityId,
      wc.city_name as cityName,
      wc.described as described,
      wc.sort AS sort,
      wc.del_state AS delState,
      wc.create_by AS createBy,
      wc.create_time AS createTime,
      wc.update_by AS updateBy,
      wc.update_time AS updateTime,
      wf.fieldCount as fieldCount,
      wf.engineNumber as engineNumber
    </sql>


    <select id="selectWindRelationCompanyByType"
            resultType="com.energy.manage.service.domain.vo.company.WindCompanyPageVo">
        SELECT
       <include refid="BASE_COMPANY_SQL"/>
        FROM
        wind_relation wr
        LEFT JOIN
        wind_company wc on wr.code_number = wc.company_code
        LEFT JOIN
        (SELECT
	    wf.company_code,
	    count(1) as fieldCount,
	    sum(wf.engine_number) as engineNumber
        FROM
	    wind_company wc
	    INNER JOIN wind_field wf ON wc.company_code = wf.company_code
        GROUP BY
	    wf.company_code) wf on wc.company_code=wf.company_code
        where 1=1
        and wr.type = #{type}
        <if test="state!=null">
        and wc.state = #{state}
        </if>
        <if test="companyName!=null">
        and wc.company_name like CONCAT("%", #{companyName} ,"%")
        </if>
        and wc.del_state = 0
        <if test="state!=null or companyName!=null">
            and
            wc.company_code in (select code_number from sys_organization_auth where role_id =#{roleId} and code_type = 'company')
        </if>
        <if test="state==null and companyName==null">
            and
            wc.create_by = #{userId}
            or
            wc.company_code in (select code_number from sys_organization_auth where role_id =#{roleId} and code_type = 'company')

        </if>
    </select>

    <select id="selectByCodeNumber" parameterType="java.lang.String" resultType="com.energy.manage.common.po.windrelation.WindRelationPO">
        select code_number,
               type,
               parent_code
        from wind_relation
        where parent_code in
        <foreach collection="codeNumbers" item="codeNumber" open="(" separator="," close=")">
            #{codeNumber,jdbcType=VARCHAR}
        </foreach>

    </select>


</mapper>
