<?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.project.business.mapper.TcProjectMapper">

    <resultMap type="TcProject" id="TcProjectResult">
        <result property="projectId"    column="project_id"    />
        <result property="projectNo"    column="project_no"    />
        <result property="projectName"    column="project_name"    />
        <result property="accountId"    column="account_id"    />
        <result property="address"    column="address"    />
        <result property="modelFlag"    column="model_flag"    />
        <result property="modelFlagName"    column="modelFlagName"    />
        <result property="type"    column="type"    />
        <result property="typeName"    column="typeName"    />
        <result property="segmentedMarket"    column="segmented_market"    />
        <result property="segmentedMarketName"    column="segmentedMarketName"    />
        <result property="areaId"    column="area_id"    />
        <result property="areaName" column="area_name"/>
        <result property="countryId"    column="country_id"    />
        <result property="countryName"    column="countryName"    />
        <result property="city"    column="city"    />
        <result property="progress"    column="progress"    />
        <result property="developer"    column="developer"    />
        <result property="planDealMonth"    column="plan_deal_month"    />
        <result property="completionYear"    column="completion_year"    />
        <result property="startTime"    column="start_time"    />
        <result property="overTime"    column="over_time"    />
        <result property="currencyId"    column="currency_id"    />
        <result property="contactPerson"    column="contact_person"    />
        <result property="contact"    column="contact"    />
        <result property="jobTitle"    column="job_title"    />
        <result property="email"    column="email"    />
        <result property="status"    column="status"    />
        <result property="productSeries"    column="product_series"    />
        <result property="solution"    column="solution"    />
        <result property="owner"    column="owner"    />
        <result property="ownerName"    column="ownerName"    />
        <result property="ownerAgent"    column="owner_agent"    />
        <result property="ownerAgentName"    column="ownerAgentName"    />
        <result property="refuseReason"    column="refuse_reason"    />
        <result property="auditPerson"    column="audit_person"    />
        <result property="delayRemark"    column="delay_remark"    />
        <result property="loseRemark"    column="lose_remark"    />
        <result property="permissionChar"    column="permission_char"    />
        <result property="delFlag"    column="del_flag"    />
        <result property="createTime"    column="create_time"    />
        <result property="createBy"    column="create_by"    />
        <result property="updateTime"    column="update_time"    />
        <result property="updateBy"    column="update_by"    />
        <result property="remark"    column="remark"    />
        <result property="keyContactPerson"    column="key_contact_person"    />
        <result property="keyContact"    column="key_contact"    />
        <result property="keyJobTitle"    column="key_job_title"    />
        <result property="keyEmail"    column="key_email"    />
        <result property="specialRemark"    column="special_remark"    />
        <result property="lastFollowTime"   column="lastFollowTime"    />
        <result property="createByName"    column="createByName"    />
        <result property="parentSaleId"    column="parentSaleId"    />
        <result property="accountNo"    column="account_no"    />
        <result property="accountName"    column="account_name"    />
        <result property="followDesc"    column="follow_desc"    />
        <result property="followTime"    column="follow_time"    />
        <result property="followPerson"    column="follow_person"    />
        <result property="deptId"    column="dept_id"    />
        <result property="leads" column="leads"/>
        <result property="deviceTotal" column="deviceTotal"/>
        <result property="priceTotal" column="priceTotal"/>
        <result property="discountFlag" column="discount_flag"/>
        <result property="agentDiscountRate" column="agent_discount_rate"/>
        <result property="countryDiscountRate" column="country_discount_rate"/>
        <result property="expectedInstallStartDate" column="expected_install_start_date"/>
        <result property="countryAbbr" column="country_abbr"/>
        <result property="loseRemark" column="lose_remark"/>
        <result property="competitor" column="competitor"/>
        <result property="reasonType" column="reason_type"/>
        <result property="reasonTypeName" column="reasonTypeName"/>
    </resultMap>

    <resultMap type="TcProjectForRelated" id="TcProjectResultForRelated"  extends="TcProjectResult">
        <result property="countryName"    column="country_name"    />
    </resultMap>

    <resultMap type="com.ruoyi.project.business.domain.TcProject" id="TcProjectResultWith"  extends="TcProjectResult">
        <collection property="machineList" ofType="com.ruoyi.project.business.domain.TcProjectEquipment">
            <result property="id"    column="item_id"    />
            <result property="projectId"    column="project_id"    />
            <result property="equipmentQuantity"    column="equipment_quantity"    />
            <result property="equipmentType"    column="equipment_type"    />
            <result property="amount"    column="amount"    />
            <result property="updateTime"    column="update_time"    />
            <result property="updateBy"    column="update_by"    />
            <result property="remark"    column="remark"    />
        </collection>
    </resultMap>

    <sql id="selectTcProjectVo">
        select project_id, project_no, project_name, account_id, address, model_flag, type, segmented_market,
               country_id, city, developer, plan_deal_month, completion_year, start_time, over_time,
               currency_id, contact_person, contact, job_title, email, status, product_series, solution,
               owner, owner_agent, refuse_reason, audit_person, delay_remark, lose_remark,
               permission_char, del_flag, create_time, create_by, update_time, update_by, remark,
               area_id, key_contact_person, key_contact, key_job_title, key_email, special_remark
        from tc_project
    </sql>

    <sql id="selectTcProjectList">
        select p.*,
               ta.account_name                                              as account_name,
               a.parent_saler_id                                            as parentSaleId,
               f.follow_desc,
               f.follow_time,
               su.nick_name                                                 as follow_person,
               u.nick_name                                                  as ownerName,
               IF(p.owner_agent = 0, 'common.head', a.agent_name)           as ownerAgentName,
               su2.dept_id,
               sum(ifnull(pe.equipment_quantity, 0))                        as deviceTotal,
               sum(ifnull(pe.equipment_quantity, 0) * ifnull(pe.amount, 0)) as priceTotal,
               a.discount_flag as discount_flag,
               a.discount                                                   as agent_discount_rate,
               c.discount                                                   as country_discount_rate,
               CASE #{language}
                   WHEN 'chinese' THEN c.country_name
                   WHEN 'english' THEN c.country_nameUS
                   WHEN 'russia' THEN c.country_nameRU
                   WHEN 'spanish' THEN c.country_nameES
                   END                                                      AS countryName
        from tc_project p
                 left join tc_account ta on p.account_id = ta.account_id
                 left join tb_agent a on a.agent_id = p.owner_agent
                 left join tb_country c on p.country_id = c.country_id
                 left join (
                  SELECT
                         tf.business_id,
                         tf.follow_time,
                         tf.create_by,
                         tf.follow_desc
                    FROM
                        tc_follow tf
						INNER JOIN ( SELECT max(follow_id) as id from tc_follow WHERE del_flag = '0'
						 group by business_id) t2 on t2.id = tf.follow_id
                    WHERE
                         tf.follow_type = '2'
                      AND  tf.del_flag = '0'
                 ) f on f.business_id = p.project_id
                 left join sys_user u on u.user_id = p.owner
                 left join sys_user su on su.user_id = f.create_by
                 left join sys_user su2 on su2.user_id = p.create_by
                 left join tc_project_equipment pe on pe.project_id = p.project_id and pe.del_flag = '0'
                 inner join (SELECT p.premession_char
                             FROM (SELECT @premessionStr := #{permissionChar} p) param,
                                  getpremessionview_chars p) permission
                            on permission.premession_char = p.permission_char
    </sql>

    <sql id="selectTcProjectListNew">
        select p.*,
               ta.account_name                                              as account_name,
               a.parent_saler_id                                            as parentSaleId,
               f.follow_desc,
               f.follow_time,
               su.nick_name                                                 as follow_person,
               u.nick_name                                                  as ownerName,
               IF(p.owner_agent = 0, 'common.head', a.agent_name)           as ownerAgentName,
               su2.dept_id,

              total.deviceTotal,
              total.priceTotal,
               a.discount_flag as discount_flag,
               a.discount                                                   as agent_discount_rate,
               c.discount                                                   as country_discount_rate,
               CASE #{language}
                   WHEN 'chinese' THEN c.country_name
                   WHEN 'english' THEN c.country_nameUS
                   WHEN 'russia' THEN c.country_nameRU
                   WHEN 'spanish' THEN c.country_nameES
                   END                                                      AS countryName
        from tc_project p
                 left join tc_account ta on p.account_id = ta.account_id
                 left join tb_agent a on a.agent_id = p.owner_agent
                 left join tb_country c on p.country_id = c.country_id
                 left join ( SELECT
                         tf.business_id,
                         tf.follow_time,
                         tf.create_by,
                         tf.follow_desc
                    FROM
                        tc_follow tf
						INNER JOIN ( SELECT max(follow_id) as id from tc_follow WHERE del_flag = '0'
						 group by business_id) t2 on t2.id = tf.follow_id
                    WHERE
                         tf.follow_type = '2'
                      AND  tf.del_flag = '0'	 ) f on f.business_id = p.project_id
                 left join sys_user u on u.user_id = p.owner
                 left join sys_user su on su.user_id = f.create_by
                 left join sys_user su2 on su2.user_id = p.create_by
                 left join tc_project_equipment pe on pe.project_id = p.project_id and pe.del_flag = '0'
                 left join (
                    select project_id,
                        SUM(IFNULL(equipment_quantity,0)) as deviceTotal,
                        SUM(IFNULL(equipment_quantity,0) * IFNULL(amount,0)) as priceTotal
                        from(
                        SELECT
                            main.project_id,
                            main.quotation_no,
                            ts.elevator_number AS equipment_quantity,
                            case
                            WHEN main.quotation_status &lt; 6 THEN	 0
                            ELSE IFNULL( ts.final_price, ts.price )
                            END AS amount
                        FROM
                            (
                            SELECT DISTINCT
                                quo.id,
                                project.project_id,
                                quo.quotation_no,
                                quo.quotation_status
                            FROM
                                tq_quotation quo
                                LEFT JOIN tc_project project ON quo.project_id = project.project_id
                                AND project.del_flag = '0'
                            WHERE
                                quo.del_flag = '0'
                            ORDER BY
                                FIELD( quo.quotation_status, '9' ) DESC,
                                id DESC
                            ) main
                            LEFT JOIN tq_specification ts ON ts.quotation_id = main.id
                            AND ts.del_flag = '0'
                        GROUP BY
                            main.quotation_no
                        union
                        SELECT
                        project_id,
                        '' AS quotation_no,
                        equipment_quantity,
                        amount
                        FROM
                        tc_project_equipment
                        where  del_flag = '0'
                    ) main
                    GROUP BY main.project_id
                  ) total on total.project_id = p.project_id
                 inner join (SELECT p.premession_char
                             FROM (SELECT @premessionStr := #{permissionChar} p) param,
                                  getpremessionview_chars p) permission
                            on permission.premession_char = p.permission_char
    </sql>

    <sql id="selectTcProjectListExport">
        select p.*,
               acc.account_name                                                              as account_name,
               f.follow_desc,
               f.follow_time,
               su.nick_name                                                                  as follow_person,
               u.nick_name                                                                   as ownerName,
               IF(p.owner_agent = 0, (CASE #{language}
                                          WHEN 'chinese' THEN '总部'
                                          WHEN 'english' THEN 'headquarters'
                                          WHEN 'russia' THEN 'Штаб - квартира'
                                          WHEN 'spanish' THEN 'Sede' END), agent.agent_name) as ownerAgentName,
               CASE #{language}
                   WHEN 'chinese' THEN c.country_name
                   WHEN 'english' THEN c.country_nameUS
                   WHEN 'russia' THEN c.country_nameRU
                   WHEN 'spanish' THEN c.country_nameES
                   END AS countryName,
               CASE #{language}
                   WHEN 'chinese' THEN ta.area_name
                   WHEN 'english' THEN ta.area_nameUS
                   WHEN 'russia' THEN ta.area_nameRU
                   WHEN 'spanish' THEN ta.area_nameES
                   END AS area_name,
               CASE #{language}
                   WHEN 'chinese' THEN t1.dict_label
                   WHEN 'english' THEN t1.dict_labelUS
                   WHEN 'russia' THEN t1.dict_labelRU
                   WHEN 'spanish' THEN t1.dict_labelES
                   END AS statusName,
               CASE #{language}
                   WHEN 'chinese' THEN t2.dict_label
                   WHEN 'english' THEN t2.dict_labelUS
                   WHEN 'russia' THEN t2.dict_labelRU
                   WHEN 'spanish' THEN t2.dict_labelES
                   END AS typeName,
               CASE #{language}
                   WHEN 'chinese' THEN t3.dict_label
                   WHEN 'english' THEN t3.dict_labelUS
                   WHEN 'russia' THEN t3.dict_labelRU
                   WHEN 'spanish' THEN t3.dict_labelES
                   END AS modelFlagName,
               CASE #{language}
                   WHEN 'chinese' THEN t5.dict_label
                   WHEN 'english' THEN t5.dict_labelUS
                   WHEN 'russia' THEN t5.dict_labelRU
                   WHEN 'spanish' THEN t5.dict_labelES
                   END AS progressName,
               CASE #{language}
                   WHEN 'chinese' THEN t4.dict_label
                   WHEN 'english' THEN t4.dict_labelUS
                   WHEN 'russia' THEN t4.dict_labelRU
                   WHEN 'spanish' THEN t4.dict_labelES
                   END AS segmentedMarketName,
               CASE #{language}
                   WHEN 'chinese' THEN t6.dict_label
                   WHEN 'english' THEN t6.dict_labelUS
                   WHEN 'russia' THEN t6.dict_labelRU
                   WHEN 'spanish' THEN t6.dict_labelES
                   END AS reasonTypeName
        from tc_project p
                 left join tc_account acc on p.account_id = acc.account_id
                 left join tb_area ta on ta.area_id = p.area_id
                 left join tb_country c on p.country_id = c.country_id
                 left join (select business_id, follow_desc, follow_time, create_by
                            from tc_follow
                            where follow_type = '2'
                              and del_flag = '0'
                            order by follow_time desc) f on f.business_id = p.project_id
                 left join sys_user u on u.user_id = p.owner
                 left join sys_user su on su.user_id = f.create_by
                 left join tb_agent agent on agent.agent_id = p.owner_agent
                 left join sys_dict_data t1 on t1.dict_type = 'project_status' and p.status = t1.dict_value
                 left join sys_dict_data t2 on t2.dict_type = 'project_type' and p.type = t2.dict_value
                 left join sys_dict_data t3 on t3.dict_type = 'project_flag' and p.model_flag = t3.dict_value
                 left join sys_dict_data t4 on t4.dict_type = 'project_market' and p.segmented_market = t4.dict_value
                 left join sys_dict_data t5 on t5.dict_type = 'project_progress' and p.progress = t5.dict_value
                   left join sys_dict_data t6 on t6.dict_type = 'project_reason_type' and p.reason_type = t6.dict_value
                 inner join (SELECT p.premession_char
                             FROM (SELECT @premessionStr := #{permissionChar} p) param,
                                  getpremessionview_chars p) permission
                            on permission.premession_char = p.permission_char
    </sql>

    <sql id="whereSql">
        <where>
            <if test="startDate != null and endDate != null"> and p.create_time between #{startDate} and #{endDate}</if>
            <if test="projectId != null"> and p.project_id = #{projectId}</if>
            <if test="projectNo != null and projectNo != ''"> and p.project_no like concat('%',#{projectNo},'%') escape '/'</if>
            <if test="areaId != null and areaId.size() > 0">
                and p.area_id in
                <foreach collection="areaId" item="item" open="(" separator="," close=")">
                    #{item}
                </foreach>
            </if>
            <if test="countryId != null and countryId.size() > 0 ">
                and p.country_id in
                <foreach collection="countryId" item="item" open="(" separator="," close=")">
                    #{item}
                </foreach>
            </if>
            <if test="city != null and city != ''"> and p.city like concat('%',#{city},'%') escape '/'</if>
            <if test="status != null and status.size() > 0 ">
                and p.status in
                <foreach collection="status" item="item" open="(" separator="," close=")">
                    #{item}
                </foreach>
            </if>
            <if test="ownerName != null  and ownerName != ''">and u.nick_name like concat('%',#{ownerName},'%') escape '/'</if>
            <if test="ownerAgent != null and ownerAgent.size() > 0">
                and p.owner_agent in
                <foreach collection="ownerAgent" item="item" open="(" separator="," close=")">
                    #{item}
                </foreach>
            </if>
            <if test="projectName != null and projectName != ''"> and p.project_name like concat('%',#{projectName},'%') escape '/'</if>
            <if test="type != null and type.size() > 0 ">
                and p.type in
                <foreach collection="type" item="item" open="(" separator="," close=")">
                    #{item}
                </foreach>
            </if>
            <if test="modelFlag != null and modelFlag != ''"> and p.model_flag = #{modelFlag}</if>
            <if test="segmentedMarket != null and segmentedMarket.size() > 0 ">
                and p.segmented_market in
                <foreach collection="segmentedMarket" item="item" open="(" separator="," close=")">
                    #{item}
                </foreach>
            </if>
            <if test="completionYear != null and completionYear != ''">
                and cast(p.completion_year as date) = #{completionYear}
            </if>
            <if test="accountId != null "> and p.account_id = #{accountId}</if>
            <if test="loginUserId != null  and loginUserId != ''">
                and (p.permission_char &lt;&gt; #{permission} or p.owner = #{loginUserId})
            </if>
            <if test="ids != null and ids.size() > 0">
                and p.project_id in
                <foreach collection="ids" item="id" open="(" separator="," close=")">
                    #{id}
                </foreach>
            </if>
            <if test="progress != null and progress.size() > 0">
                and CONCAT(p.progress,'0') in
                <foreach collection="progress" item="item" open="(" separator="," close=")">
                    CONCAT( #{item} ,'0')
                </foreach>
            </if>
            <if test="expectedInstallStartDateStart != null and expectedInstallStartDateEnd != null">
                and p.expected_install_start_date between #{expectedInstallStartDateStart} and #{expectedInstallStartDateEnd}
            </if>
            and p.del_flag = '0'
        </where>
        group by p.project_id
        order by p.project_id desc
    </sql>
    <sql id="whereExportSql">
        <where>
            <if test="projectId != null"> and p.project_id = #{projectId}</if>
            <if test="projectNo != null and projectNo != ''"> and p.project_no like concat('%',#{projectNo},'%') escape '/'</if>
            <if test="areaId != null and areaId.size() > 0">
                and p.area_id in
                <foreach collection="areaId" item="item" open="(" separator="," close=")">
                    #{item}
                </foreach>
            </if>
            <if test="countryId != null and countryId.size() > 0 ">
                and p.country_id in
                <foreach collection="countryId" item="item" open="(" separator="," close=")">
                    #{item}
                </foreach>
            </if>
            <if test="city != null and city != ''"> and p.city like concat('%',#{city},'%') escape '/'</if>
            <if test="status != null and status.size() > 0 ">
                and p.status in
                <foreach collection="status" item="item" open="(" separator="," close=")">
                    #{item}
                </foreach>
            </if>
            <if test="ownerName != null  and ownerName != ''">and u.nick_name like concat('%',#{ownerName},'%') escape '/'</if>
            <if test="ownerAgent != null and ownerAgent.size() > 0">
                and p.owner_agent in
                <foreach collection="ownerAgent" item="item" open="(" separator="," close=")">
                    #{item}
                </foreach>
            </if>
            <if test="projectName != null and projectName != ''"> and p.project_name like concat('%',#{projectName},'%') escape '/'</if>
            <if test="type != null and type.size() > 0 ">
                and p.type in
                <foreach collection="type" item="item" open="(" separator="," close=")">
                    #{item}
                </foreach>
            </if>
            <if test="modelFlag != null and modelFlag != ''"> and p.model_flag = #{modelFlag}</if>
            <if test="segmentedMarket != null and segmentedMarket.size() > 0 ">
                and p.segmented_market in
                <foreach collection="segmentedMarket" item="item" open="(" separator="," close=")">
                    #{item}
                </foreach>
            </if>
            <if test="completionYear != null and completionYear != ''">
                and cast(p.completion_year as date) = #{completionYear}
            </if>
            <if test="accountId != null "> and p.account_id = #{accountId}</if>
            <if test="loginUserId != null  and loginUserId != ''">
                and (p.permission_char &lt;&gt; #{permission} or p.owner = #{loginUserId})
            </if>
            <if test="ids != null and ids.size() > 0">
                and p.project_id in
                <foreach collection="ids" item="id" open="(" separator="," close=")">
                    #{id}
                </foreach>
            </if>
            <if test="progress != null and progress.size() > 0">
                and p.progress in
                <foreach collection="progress" item="item" open="(" separator="," close=")">
                    #{item}
                </foreach>
            </if>
            and p.del_flag = '0'
        </where>
        group by p.project_id
        order by p.project_id desc
    </sql>

    <select id="selectTcProjectList" parameterType="com.ruoyi.project.business.domain.vo.selectParam.ProjectParam" resultMap="TcProjectResult">
        <include refid="selectTcProjectList"/>
        <include refid="whereSql"/>
    </select>

    <select id="selectTcProjectListExport" parameterType="com.ruoyi.project.business.domain.vo.selectParam.ProjectParam" resultMap="TcProjectResult">
        <include refid="selectTcProjectListExport"/>
        <include refid="whereExportSql"/>
    </select>

    <select id="selectProjectListByLoginId" parameterType="TcProject" resultMap="TcProjectResultForRelated">
        SELECT
            project_id,
            project_no,
            project_name,
            account_id,
            model_flag,
            type,
            segmented_market,
            t1.country_id,
            city,
            developer,
            start_time,
            over_time,
            contact_person,
            contact,
            STATUS,
            CASE #{language}
                WHEN 'english' THEN tb1.country_nameUS
                WHEN 'russia' THEN tb1.country_nameRU
                WHEN 'spanish' THEN tb1.country_nameES
                ELSE tb1.country_name
            END AS country_name
        FROM tc_project t1
            LEFT JOIN tb_country tb1 ON tb1.country_id = t1.country_id
        WHERE
            t1.del_flag = 0 and t1.owner = #{loginId}
    </select>

    <select id="selectProjectListByQuery" parameterType="TcProject" resultMap="TcProjectResultForRelated">
        SELECT
            project_id,
            project_no,
            project_name,
            account_id,
            model_flag,
            type,
            segmented_market,
            t1.country_id,
            city,
            developer,
            start_time,
            over_time,
            contact_person,
            contact,
            STATUS,
            CASE #{language}
                WHEN 'english' THEN tb1.country_nameUS
                WHEN 'russia' THEN tb1.country_nameRU
                WHEN 'spanish' THEN tb1.country_nameES
                ELSE tb1.country_name
            END AS country_name
        FROM tc_project t1
             LEFT JOIN tb_country tb1 ON tb1.country_id = t1.country_id
        WHERE
            t1.del_flag = 0
            and t1.owner = #{loginId}
            and t1.status not in ('01','02')
        <if test="query != null  and query != ''">
            and  (
            t1.project_no like concat('%',#{query},'%') or
            t1.project_name like concat('%',#{query},'%') or
            tb1.country_name like concat('%',#{query},'%') or
            tb1.country_nameUS like concat('%',#{query},'%') or
            tb1.country_nameRU like concat('%',#{query},'%') or
            tb1.country_nameES like concat('%',#{query},'%') or
            t1.city like concat('%',#{query},'%')
            )
        </if>
    </select>

    <select id="selectProjectListByProjectId" parameterType="java.lang.Long" resultMap="TcProjectResultForRelated">
        SELECT
            project_id,
            project_no,
            project_name,
            account_id,
            model_flag,
            type,
            segmented_market,
            t1.country_id,
            city,
            developer,
            start_time,
            over_time,
            contact_person,
            contact,
            STATUS,
            tb1.country_name
        FROM tc_project t1
             LEFT JOIN tb_country tb1 ON tb1.country_id = t1.country_id
        WHERE 1 = 1
        <if test="projectId != null  and projectId != ''"> and t1.project_id = #{projectId} </if>

    </select>

    <select id="selectProjectListByCycle" parameterType="Long" resultMap="TcProjectResult">
        SELECT
            project_id,
            project_no,
            project_name,
            account_id,
            model_flag,
            type,
            segmented_market,
            country_id,
            city,
            developer,
            start_time,
            over_time,
            contact_person,
            contact,
            STATUS,
            owner,
            owner_agent,
            permission_char,
            del_flag,
            create_time,
            create_by,
            update_time,
            update_by,
            remark
        FROM tc_project
        WHERE del_flag = 0
              AND progress NOT IN ('90%', '100%', '0%','0% ')
              AND DATEDIFF(CURRENT_DATE, create_time) >= 10
              AND project_id NOT IN (
                SELECT
                tc_follow.business_id AS project_no
                FROM tc_follow
                WHERE follow_type = '2'
                    AND DATEDIFF(CURRENT_DATE, CONCAT(YEAR(tc_follow.follow_time),  '-', LPAD(MONTH( tc_follow.follow_time ), 2, '0'), '-', LPAD(DAY(tc_follow.follow_time), 2, '0'))) &lt; #{modelFlag}
                )
    </select>

    <select id="selectTcProjectByProjectId" parameterType="Long" resultMap="TcProjectResult">
        select p.*, a.account_no, a.account_name,c.country_abbr from tc_project p
            left join tc_account a on p.account_id = a.account_id
            left join tb_country c on c.country_id = p.country_id
        where p.project_id = #{projectId}
    </select>

    <select id="selectTcProjectByProjectIdandChar"  resultMap="TcProjectResult">
        select p.*, a.account_no, a.account_name from tc_project p
          left join tc_account a on p.account_id = a.account_id
          inner join (SELECT p.premession_char
                             FROM (SELECT @premessionStr := #{permissionChar} p) param,
                                  getpremessionview_chars p) permission
                            on permission.premession_char = p.permission_char
           where p.project_id = #{projectId}
    </select>

    <select id="selectProjectListByAccount" parameterType="TcProject" resultMap="TcProjectResult">
        select p.*, u.nick_name as createByName,
        total.deviceTotal,
        total.priceTotal
        from tc_project p
        left join sys_user u on p.create_by = u.user_id
        left join tc_project_equipment pe on pe.project_id = p.project_id and pe.del_flag = '0'
         left join (
                    select project_id,
                        SUM(IFNULL(equipment_quantity,0)) as deviceTotal,
                        SUM(IFNULL(equipment_quantity,0) * IFNULL(amount,0)) as priceTotal
                        from(
                        SELECT
                            main.project_id,
                            main.quotation_no,
                            ts.elevator_number AS equipment_quantity,
                            case
                            WHEN main.quotation_status &lt; 6 THEN	 0
                            ELSE IFNULL( ts.final_price, ts.price )
                            END AS amount
                        FROM
                            (
                            SELECT DISTINCT
                                quo.id,
                                project.project_id,
                                quo.quotation_no,
                                quo.quotation_status
                            FROM
                                tq_quotation quo
                                LEFT JOIN tc_project project ON quo.project_id = project.project_id
                                AND project.del_flag = '0'
                            WHERE
                                quo.del_flag = '0'
                            ORDER BY
                                FIELD( quo.quotation_status, '9' ) DESC,
                                id DESC
                            ) main
                            LEFT JOIN tq_specification ts ON ts.quotation_id = main.id
                            AND ts.del_flag = '0'
                        GROUP BY
                            main.quotation_no
                        union
                        SELECT
                        project_id,
                        '' AS quotation_no,
                        equipment_quantity,
                        amount
                        FROM
                        tc_project_equipment
                        where  del_flag = '0'
                    ) main
                    GROUP BY main.project_id
                  ) total on total.project_id = p.project_id
        where p.account_id = #{accountId} and p.del_flag = '0'
        group by p.project_id
        order by p.project_id desc
    </select>

    <select id="selectUnFollowedList" resultMap="TcProjectResult">
        select TT.*
        from (SELECT tp.*,
                     COALESCE(pe_data.deviceTotal, 0) AS deviceTotal,
                     COALESCE(pe_data.priceTotal, 0) AS priceTotal,
                     ta.area_name,
                     (select follow_time
                      from tc_follow t
                      where t.business_id = tp.project_id
                        and t.follow_type = '2'
                      order by t.follow_time desc
                      limit 1) lastFollowTime
              FROM tc_project tp
                       left join tc_follow tf on tp.project_id = tf.business_id and tf.follow_type = '2'
                  and tf.follow_time between #{startDate} and #{endDate}
              left join tb_area ta on tp.area_id = ta.area_id
                       LEFT JOIN (
                  SELECT
                      pe.project_id,
                      SUM(IFNULL(pe.equipment_quantity, 0)) AS deviceTotal,
                      SUM(IFNULL(pe.total_price, 0)) AS priceTotal
                  FROM
                      tc_project_equipment pe
                  WHERE
                      pe.del_flag = '0'
                  GROUP BY
                      pe.project_id
              ) pe_data ON tp.project_id = pe_data.project_id

              WHERE tp.del_flag = 0
                and tp.status not in ('01', '02')
                and tp.progress not in ('0%', '0% ')
                and tf.follow_id is null) TT
                 inner join (SELECT p.premession_char FROM (SELECT @premessionStr:=#{permissionChar} p) param , getpremessionview_chars p)
                     permission on permission.premession_char = TT.permission_char
    </select>

    <select id="selectCountByProjectName" resultType="java.lang.Integer">
        select count(1) from tc_project where del_flag = '0'
        and project_name = #{projectName} and permission_char = #{permissionChar}
        <if test="projectId != null">
            and project_id != #{projectId}
        </if>
    </select>

    <select id="selectCountByAccountId" resultType="java.lang.Integer">
        select count(1) from tc_project where del_flag = '0' and account_id = #{accountId}
    </select>
    <select id="existProjectByAgentIds" resultType="java.lang.Integer">
        select 1 from tc_project where del_flag = '0' and owner_agent in
        <foreach collection="array" item="item" open="(" separator="," close=")">
            #{item}
        </foreach>
        limit 1
    </select>

    <select id="selectTcProjectListApp" resultMap="TcProjectResult">
        select p.project_id, p.project_name, p.developer, p.update_time,
               a.area_name as area_name, u.nick_name as createByName, d.dict_label as typeName,
               p.city,ta.agent_name as ownerAgentName,c.country_name as countryName,tac.account_name
        from tc_project p
        left join tb_area a on p.area_id = a.area_id
        left join sys_user u on u.user_id = p.create_by
        left join tb_agent ta on p.owner_agent = ta.agent_id
        left join tc_account tac on p.account_id = tac.account_id
        left join tb_country c on p.country_id = c.country_id
        left join sys_dict_data d on d.dict_type = 'project_type' and d.dict_value = p.type
        inner join (SELECT p.premession_char FROM (SELECT @premessionStr:= #{permissionChar} p) param , getpremessionview_chars p
        ) permission on permission.premession_char = p.permission_char
        where a.del_flag = '0' 	and p.del_flag = '0'  and p.status = '01' and ta.parent_saler_id = #{userId}
    </select>
    <select id="selectQuotationInfo" resultType="com.ruoyi.project.business.domain.TcProject">

        select tq1.project_id,
               sum(ts.elevator_number)            as elevator_number,
               tem.elevator_type,
               sum(ts.elevator_number * ts.price) as elevatorAmount

        from tq_quotation tq1
                 join tq_specification ts on tq1.id = ts.quotation_id
                 left join tp_elevator_model tem on ts.elevator_model_id = tem.id
        where tq1.del_flag = '0'
            and tq1.project_id in
            <foreach collection="projectIds" item="projectId" open="(" separator="," close=")">
                #{projectId}
            </foreach>
          and tq1.version =
              (select max(version)
               from tq_quotation tq2
               where tq2.project_id = tq1.project_id
                 and tq1.quotation_no = tq2.quotation_no)
        group by tq1.project_id, elevator_type;
    </select>

    <insert id="insertTcProject" parameterType="TcProject" useGeneratedKeys="true" keyProperty="projectId">
        insert into tc_project
        <trim prefix="(" suffix=")" suffixOverrides=",">
            <if test="projectNo != null">project_no,</if>
            <if test="projectName != null">project_name,</if>
            <if test="accountId != null">account_id,</if>
            <if test="address != null">address,</if>
            <if test="modelFlag != null">model_flag,</if>
            <if test="type != null">type,</if>
            <if test="segmentedMarket != null">segmented_market,</if>
            <if test="countryId != null">country_id,</if>
            <if test="city != null">city,</if>
            <if test="progress != null">progress,</if>
            <if test="developer != null">developer,</if>
            <if test="planDealMonth != null">plan_deal_month,</if>
            <if test="completionYear != null">completion_year,</if>
            <if test="startTime != null">start_time,</if>
            <if test="overTime != null">over_time,</if>
            <if test="currencyId != null">currency_id,</if>
            <if test="contactPerson != null">contact_person,</if>
            <if test="contact != null">contact,</if>
            <if test="jobTitle != null">job_title,</if>
            <if test="email != null">email,</if>
            <if test="status != null">status,</if>
            <if test="productSeries != null">product_series,</if>
            <if test="solution != null">solution,</if>
            <if test="owner != null">owner,</if>
            <if test="ownerAgent != null">owner_agent,</if>
            <if test="refuseReason != null">refuse_reason,</if>
            <if test="auditPerson != null">audit_person,</if>
            <if test="delayRemark != null">delay_remark,</if>
            <if test="loseRemark != null">lose_remark,</if>
            <if test="permissionChar != null">permission_char,</if>
            <if test="areaId != null">area_id,</if>
            <if test="keyContactPerson != null">key_contact_person,</if>
            <if test="keyContact != null">key_contact,</if>
            <if test="keyJobTitle != null">key_job_title,</if>
            <if test="keyEmail != null">key_email,</if>
            <if test="specialRemark != null">special_remark,</if>
            <if test="delFlag != null">del_flag,</if>
            <if test="createTime != null">create_time,</if>
            <if test="createBy != null">create_by,</if>
            <if test="updateTime != null">update_time,</if>
            <if test="updateBy != null">update_by,</if>
            <if test="remark != null">remark,</if>
            <if test="equipmentQuantity != null">equipment_quantity,</if>
            <if test="equipmentType != null">equipment_type,</if>
            <if test="amount != null">amount,</if>
            <if test="expectedInstallStartDate != null">expected_install_start_date,</if>
        </trim>
        <trim prefix="values (" suffix=")" suffixOverrides=",">
            <if test="projectNo != null">#{projectNo},</if>
            <if test="projectName != null">#{projectName},</if>
            <if test="accountId != null">#{accountId},</if>
            <if test="address != null">#{address},</if>
            <if test="modelFlag != null">#{modelFlag},</if>
            <if test="type != null">#{type},</if>
            <if test="segmentedMarket != null">#{segmentedMarket},</if>
            <if test="countryId != null">#{countryId},</if>
            <if test="city != null">#{city},</if>
            <if test="progress != null">#{progress},</if>
            <if test="developer != null">#{developer},</if>
            <if test="planDealMonth != null">#{planDealMonth},</if>
            <if test="completionYear != null">#{completionYear},</if>
            <if test="startTime != null">#{startTime},</if>
            <if test="overTime != null">#{overTime},</if>
            <if test="currencyId != null">#{currencyId},</if>
            <if test="contactPerson != null">#{contactPerson},</if>
            <if test="contact != null">#{contact},</if>
            <if test="jobTitle != null">#{jobTitle},</if>
            <if test="email != null">#{email},</if>
            <if test="status != null">#{status},</if>
            <if test="productSeries != null">#{productSeries},</if>
            <if test="solution != null">#{solution},</if>
            <if test="owner != null">#{owner},</if>
            <if test="ownerAgent != null">#{ownerAgent},</if>
            <if test="refuseReason != null">#{refuseReason},</if>
            <if test="auditPerson != null">#{auditPerson},</if>
            <if test="delayRemark != null">#{delayRemark},</if>
            <if test="loseRemark != null">#{loseRemark},</if>
            <if test="permissionChar != null">#{permissionChar},</if>
            <if test="areaId != null">#{areaId},</if>
            <if test="keyContactPerson != null">#{keyContactPerson},</if>
            <if test="keyContact != null">#{keyContact},</if>
            <if test="keyJobTitle != null">#{keyJobTitle},</if>
            <if test="keyEmail != null">#{keyEmail},</if>
            <if test="specialRemark != null">#{specialRemark},</if>
            <if test="delFlag != null">#{delFlag},</if>
            <if test="createTime != null">#{createTime},</if>
            <if test="createBy != null">#{createBy},</if>
            <if test="updateTime != null">#{updateTime},</if>
            <if test="updateBy != null">#{updateBy},</if>
            <if test="remark != null">#{remark},</if>
            <if test="equipmentQuantity != null">#{equipmentQuantity},</if>
            <if test="equipmentType != null">#{equipmentType},</if>
            <if test="amount != null">#{amount},</if>
            <if test="expectedInstallStartDate != null">#{expectedInstallStartDate},</if>
        </trim>
    </insert>

    <update id="updateTcProject" parameterType="TcProject">
        update tc_project
        <trim prefix="SET" suffixOverrides=",">
            <if test="projectNo != null">project_no = #{projectNo},</if>
            <if test="projectName != null">project_name = #{projectName},</if>
            <if test="accountId != null">account_id = #{accountId},</if>
            <if test="address != null">address = #{address},</if>
            <if test="modelFlag != null">model_flag = #{modelFlag},</if>
            <if test="type != null">type = #{type},</if>
            <if test="segmentedMarket != null">segmented_market = #{segmentedMarket},</if>
            <if test="countryId != null">country_id = #{countryId},</if>
            <if test="city != null">city = #{city},</if>
            <if test="progress != null and progress != ''">progress = #{progress},</if>
            <if test="developer != null">developer = #{developer},</if>
            <if test="planDealMonth != null">plan_deal_month = #{planDealMonth},</if>
            <if test="completionYear != null">completion_year = #{completionYear},</if>
            <if test="startTime != null">start_time = #{startTime},</if>
            <if test="overTime != null">over_time = #{overTime},</if>
            <if test="currencyId != null">currency_id = #{currencyId},</if>
            <if test="contactPerson != null">contact_person = #{contactPerson},</if>
            <if test="contact != null">contact = #{contact},</if>
            <if test="jobTitle != null">job_title = #{jobTitle},</if>
            <if test="email != null">email = #{email},</if>
            <if test="status != null">status = #{status},</if>
            <if test="productSeries != null">product_series = #{productSeries},</if>
            <if test="solution != null">solution = #{solution},</if>
            <if test="owner != null">owner = #{owner},</if>
            <if test="ownerAgent != null">owner_agent = #{ownerAgent},</if>
            <if test="refuseReason != null">refuse_reason = #{refuseReason},</if>
            <if test="auditPerson != null">audit_person = #{auditPerson},</if>
            <if test="delayRemark != null">delay_remark = #{delayRemark},</if>
            <if test="loseRemark != null">lose_remark = #{loseRemark},</if>
            <if test="permissionChar != null">permission_char = #{permissionChar},</if>
            <if test="areaId != null">area_id = #{areaId},</if>
            <if test="keyContactPerson != null">key_contact_person = #{keyContactPerson},</if>
            <if test="keyContact != null">key_contact = #{keyContact},</if>
            <if test="keyJobTitle != null">key_job_title = #{keyJobTitle},</if>
            <if test="keyEmail != null">key_email = #{keyEmail},</if>
            <if test="specialRemark != null">special_remark = #{specialRemark},</if>
            <if test="delFlag != null">del_flag = #{delFlag},</if>
            <if test="createTime != null">create_time = #{createTime},</if>
            <if test="createBy != null">create_by = #{createBy},</if>
            <if test="updateTime != null">update_time = #{updateTime},</if>
            <if test="updateBy != null">update_by = #{updateBy},</if>
            <if test="remark != null">remark = #{remark},</if>
            <if test="competitor != null and competitor != ''">
                competitor = #{competitor},
            </if>
            <if test="reasonType != null">reason_type = #{reasonType},</if>
        </trim>
        where project_id = #{projectId}
    </update>

    <update id="updateTcProjectAll">
        update tc_project
        <trim prefix="SET" suffixOverrides=",">
            project_no = #{projectNo},
            project_name = #{projectName},
            account_id = #{accountId},
            address = #{address},
            model_flag = #{modelFlag},
            type = #{type},
            segmented_market = #{segmentedMarket},
            country_id = #{countryId},
            city = #{city},
            progress = #{progress},
            developer = #{developer},
            plan_deal_month = #{planDealMonth},
            completion_year = #{completionYear},
            start_time = #{startTime},
            over_time = #{overTime},
            currency_id = #{currencyId},
            contact_person = #{contactPerson},
            contact = #{contact},
            job_title = #{jobTitle},
            email = #{email},
            status = #{status},
            product_series = #{productSeries},
            solution = #{solution},
            owner = #{owner},
            owner_agent = #{ownerAgent},
            refuse_reason = #{refuseReason},
            audit_person = #{auditPerson},
            delay_remark = #{delayRemark},
            lose_remark = #{loseRemark},
            permission_char = #{permissionChar},
            area_id = #{areaId},
            key_contact_person = #{keyContactPerson},
            key_contact = #{keyContact},
            key_job_title = #{keyJobTitle},
            key_email = #{keyEmail},
            special_remark = #{specialRemark},
            del_flag = #{delFlag},
            create_time = #{createTime},
            create_by = #{createBy},
            update_time = #{updateTime},
            update_by = #{updateBy},
            remark = #{remark},
            expected_install_start_date = #{expectedInstallStartDate},
            <if test="equipmentQuantity != null"> equipment_quantity = #{equipmentQuantity},</if>
            <if test="equipmentType != null">equipment_type = #{equipmentType},</if>
            <if test="amount != null">amount = #{amount},</if>
            <if test="reasonType != null"> reason_type = #{reasonType},</if>
            <if test="competitor != null">competitor = #{competitor},</if>
        </trim>
        where project_id = #{projectId}
    </update>

    <update id="deleteTcProjectByProjectId" parameterType="Long">
        update tc_project set del_flag = '1' where project_id = #{projectId}
    </update>

    <update id="deleteTcProjectByProjectIds" parameterType="String">
        update tc_project set del_flag = '1' where project_id in
        <foreach item="projectId" collection="array" open="(" separator="," close=")">
            #{projectId}
        </foreach>
    </update>

    <select id="selectAreasByCurUser" resultType="java.lang.Long">
        select distinct a.area_id
        from tc_project a
                 inner join (SELECT p.premession_char
                             FROM (SELECT @premessionStr := #{permissionChar} p) param,
                                  getpremessionview_chars p) permission
                            on permission.premession_char = a.permission_char
        where a.del_flag = '0'
    </select>
    <select id="selectCountriesByCurUser" resultType="java.lang.Long">
        select distinct a.country_id
        from tc_project a
                 inner join (SELECT p.premession_char
                             FROM (SELECT @premessionStr := #{permissionChar} p) param,
                                  getpremessionview_chars p) permission
                            on permission.premession_char = a.permission_char
        where a.del_flag = '0'
    </select>


    <select id="selectTcProjectListNew" parameterType="com.ruoyi.project.business.domain.vo.selectParam.ProjectParam" resultMap="TcProjectResult">
        <include refid="selectTcProjectList"/>
        <include refid="whereSql"/>
    </select>

    <select id="selectTcProjectListNewWeb" parameterType="com.ruoyi.project.business.domain.vo.selectParam.ProjectParam" resultMap="TcProjectResult">
        <include refid="selectTcProjectListNew"/>
        <include refid="whereSql"/>
    </select>
    <select id="getNewVersion" resultType="java.lang.Long">
        select ifnull(max(version), 0) + 1 from tc_project_history where project_id = #{projectId}
    </select>
    <!--查询当天实际大于客户决定日期的项目-->
    <select id="selectProjectListJDRQ" resultMap="TcProjectResult">
        SELECT
            project_id,
            project_no,
            project_name,
            owner
        FROM tc_project
        WHERE del_flag = 0
              AND progress NOT IN ('90%', '100%', '0%','0% ')
              AND plan_deal_month is not null
              AND DATEDIFF(CURRENT_DATE, plan_deal_month) > 0
    </select>
    <select id="getProjectName" resultType="java.lang.String">
        select project_name
        FROM tc_project
        WHERE del_flag = 0 AND owner_agent = #{ownerAgent}
    </select>

    <select id="getAgentProjectStatisticsList" parameterType="com.ruoyi.project.business.domain.vo.board.AgentProjectStatistics"
            resultType="com.ruoyi.project.business.domain.vo.board.AgentProjectStatisticsVo">
        select max(t.area_id) as areaId,max(t.area_name) as areaName,max(t.city) as city,t.country_id as countryId,
               t.countryName as countryName,t.account_name as accountName,
               max(t.owner_agent) as ownerAgent,max(t.ownerAgentName) as ownerAgentName,
               count(t.progress = '100%' or null) as completeProjectQty,
               count(t.progress like '0% ' or null) as lostProjectQty,
               sum(IF(t.progress = '100%',t.deviceTotal,null)) as completeProjectEquipmentQty,
               sum(IF(t.progress like '0% ',t.deviceTotal,null)) as lostProjectEquipmentQty,
               FORMAT(sum(IF( t.progress = '100%', t.priceTotal, NULL )),2) AS completeProjectPrice,
               FORMAT(sum(IF( t.progress like '0% ', t.priceTotal, NULL )),2) AS lostProjectPrice,
               count(t.project_id) as sumProjectQty,
               sum(t.deviceTotal) as sumProjectEquipmentQty,
               FORMAT(sum(t.priceTotal),2) AS sumProjectPrice,
               ROUND(count(t.progress = '100%' or null) / count(t.project_id) * 100, 2) as completionRate,
               ROUND(count(t.progress like '0% ' or null) / count(t.project_id) * 100, 2) as lostOrderRate
        from (
            select p.*,
                   ta.account_name    as account_name,
                   a.parent_saler_id  as parentSaleId,
                   f.follow_desc,
                   f.follow_time,
                   su.nick_name       as follow_person,
                   u.nick_name        as ownerName,
                   IF(p.owner_agent = 0, 'common.head', a.agent_name)  as ownerAgentName,
                   su2.dept_id,
                   total.deviceTotal,
                   IF(ISNULL(tc.exchange_rate),total.priceTotal,(total.priceTotal / tc.exchange_rate ))as priceTotal,
                   a.discount_flag as discount_flag,
                   a.discount   as agent_discount_rate,
                   c.discount   as country_discount_rate,
                   CASE #{language}
                       WHEN 'chinese' THEN c.country_name
                       WHEN 'english' THEN c.country_nameUS
                       WHEN 'russia' THEN c.country_nameRU
                       WHEN 'spanish' THEN c.country_nameES
                       END  AS countryName,
                    CASE #{language}
                    WHEN 'chinese' THEN tba.area_name
                    WHEN 'english' THEN tba.area_nameUS
                    WHEN 'russia' THEN tba.area_nameRU
                    WHEN 'spanish' THEN tba.area_nameES
                    END   AS area_name,
                    CASE p.progress
                    WHEN '100%' THEN total.deviceTotal
                    END as completeDeviceTotal,
                    CASE p.progress
                    WHEN '0% ' THEN total.deviceTotal
                    END as lostDeviceTotal,
                    CASE p.progress
                    WHEN '100%' THEN
                        IF(ISNULL(tc.exchange_rate),total.priceTotal,(total.priceTotal / tc.exchange_rate ))
                    END as completePriceTotal,
                    CASE p.progress
                    WHEN '0% ' THEN
                         IF(ISNULL(tc.exchange_rate),total.priceTotal,(total.priceTotal / tc.exchange_rate ))
                    END as lostPriceTotal
            from tc_project p
                     left join tb_area tba on p.area_id = tba.area_id
                     left join tc_account ta on p.account_id = ta.account_id
                     left join tb_agent a on a.agent_id = p.owner_agent
                     left join tb_country c on p.country_id = c.country_id
                     left join (select business_id, follow_desc, follow_time, create_by
                                from tc_follow
                                where follow_type = '2'
                                  and del_flag = '0'
                                order by ifnull(update_time, create_time)) f on f.business_id = p.project_id
                     left join sys_user u on u.user_id = p.owner
                     left join sys_user su on su.user_id = f.create_by
                     left join sys_user su2 on su2.user_id = p.create_by
                     left join tc_project_equipment pe on pe.project_id = p.project_id and pe.del_flag = '0'
                     left join (
                        select project_id,
                               SUM(IFNULL(equipment_quantity,0)) as deviceTotal,
                               SUM(IFNULL(equipment_quantity,0) * IFNULL(amount,0)) as priceTotal
                        from(
                            SELECT
                                main.project_id,
                                main.quotation_no,
                                ts.elevator_number AS equipment_quantity,
                                case
                                WHEN main.quotation_status &lt; 6 THEN	 0
                                ELSE IFNULL( ts.final_price, ts.price )
                                END AS amount
                            FROM
                            (
                                SELECT DISTINCT
                                quo.id,
                                project.project_id,
                                quo.quotation_no,
                                quo.quotation_status
                                FROM
                                tq_quotation quo
                                LEFT JOIN tc_project project ON quo.project_id = project.project_id
                                AND project.del_flag = '0'
                                WHERE
                                quo.del_flag = '0'
                                ORDER BY
                                FIELD( quo.quotation_status, '9' ) DESC,
                                id DESC
                            ) main
                            LEFT JOIN tq_specification ts ON ts.quotation_id = main.id
                            AND ts.del_flag = '0'
                            GROUP BY
                                main.quotation_no
                            union
                            SELECT
                                project_id,
                                '' AS quotation_no,
                                equipment_quantity,
                                amount
                            FROM
                            tc_project_equipment
                            where  del_flag = '0'
                            ) main
                        GROUP BY main.project_id
                     ) total on total.project_id = p.project_id
                     left join tb_currency as tc on p.currency_id = tc.currency_id and tc.del_flag = '0'
                     inner join (SELECT p.premession_char
                                 FROM (SELECT @premessionStr := #{permissionChar} p) param,
                                      getpremessionview_chars p) permission
                                on permission.premession_char = p.permission_char
            <where>
                DATE_FORMAT(p.create_time, '%Y') = #{yearParam}
                and p.del_flag = '0' and p.status = '03'
                <if test="accountName != null  and accountName != ''">and ta.account_name like concat('%',#{accountName},'%') escape '/'</if>
                <if test="areaId != null and areaId.size() > 0">
                    and p.area_id in
                    <foreach collection="areaId" item="item" open="(" separator="," close=")">
                        #{item}
                    </foreach>
                </if>
                <if test="countryId != null and countryId.size() > 0 ">
                    and p.country_id in
                    <foreach collection="countryId" item="item" open="(" separator="," close=")">
                        #{item}
                    </foreach>
                </if>
                <if test="city != null and city != ''"> and p.city like concat('%',#{city},'%') escape '/'</if>
                <if test="ownerAgent != null and ownerAgent.size() > 0">
                    and p.owner_agent in
                    <foreach collection="ownerAgent" item="item" open="(" separator="," close=")">
                        #{item}
                    </foreach>
                </if>
            </where>
            group by p.project_id
            order by p.project_id desc
        ) t
        group by t.ownerAgentName,t.account_name
    </select>

    <select id="getAgentCompleteOrderList" parameterType="com.ruoyi.project.business.domain.vo.board.AgentCompleteOrder"
            resultType="com.ruoyi.project.business.domain.vo.board.AgentCompleteOrderVo">
        select tcl.agent_id as agentId,tcl.area_id as areaId,tcl.country_id as countryId,tcl.city,
                FORMAT(sum(tcl.amount_of_money),2) AS shippedPrice,
               sum(tcl.count) as shippedQty,
			   max(IF(tcl.agent_id = 0, 'common.head', ta.agent_name)) as agentName,
			   max(tba.area_name) as areaName,max(c.country_name) as countryName
        from tq_contract_lift as tcl
        left join tb_agent as ta on tcl.agent_id = ta.agent_id
        left join tb_area tba on tcl.area_id = tba.area_id
        left join tb_country c on tcl.country_id = c.country_id
        where
            tcl.del_flag = '0'
          and ta.first_cooperation_year = #{yearParam}
          and tcl.production_order_status = '1'
          <if test="areaId != null and areaId.size() > 0">
              and tcl.area_id in
              <foreach collection="areaId" item="item" open="(" separator="," close=")">
                  #{item}
              </foreach>
          </if>
          <if test="countryId != null and countryId.size() > 0 ">
              and tcl.country_id in
              <foreach collection="countryId" item="item" open="(" separator="," close=")">
                  #{item}
              </foreach>
          </if>
          <if test="agentId != null and agentId.size() > 0">
              and tcl.agent_id in
              <foreach collection="agentId" item="item" open="(" separator="," close=")">
                  #{item}
              </foreach>
          </if>
          <if test="city != null and city != ''"> and tcl.city like concat('%',#{city},'%') escape '/'</if>
        group by tcl.agent_id,tcl.area_id,tcl.country_id,tcl.city
    </select>

    <select id="getAccountCompleteOrderList" parameterType="com.ruoyi.project.business.domain.vo.board.AgentCompleteOrder"
            resultType="com.ruoyi.project.business.domain.vo.board.AccountCompleteOrderVo">
        SELECT
        tcl.end_customers AS accountId,
        max(ta.area_id) AS areaId,
        max(ta.country_id) AS countryId,
        max(ta.city) as city,
        FORMAT(IF(tcl.production_order_status = '1',tcl.amount_of_money,null),2) AS shippedPrice,
        sum( tcl.count ) AS annualProcurementQty,
        sum(IF(tcl.production_order_status = '1',tcl.count,null)) as shippedQty,
        max( ta.account_name ) AS accountName,
        max( tba.area_name ) AS areaName,
        max( c.country_name ) AS countryName
        FROM
        tq_contract_lift AS tcl
        LEFT JOIN tc_account AS ta ON tcl.end_customers = ta.account_id
        LEFT JOIN tb_area tba ON ta.area_id = tba.area_id
        LEFT JOIN tb_country c ON ta.country_id = c.country_id
        WHERE
        tcl.del_flag = '0'
        and DATE_FORMAT(ta.begin_year, '%Y') = #{yearParam}
        <if test="areaId != null and areaId.size() > 0">
            and tcl.area_id in
            <foreach collection="areaId" item="item" open="(" separator="," close=")">
                #{item}
            </foreach>
        </if>
        <if test="countryId != null and countryId.size() > 0 ">
            and tcl.country_id in
            <foreach collection="countryId" item="item" open="(" separator="," close=")">
                #{item}
            </foreach>
        </if>
        <if test="agentId != null and agentId.size() > 0">
            and tcl.agent_id in
            <foreach collection="agentId" item="item" open="(" separator="," close=")">
                #{item}
            </foreach>
        </if>
        <if test="city != null and city != ''"> and tcl.city like concat('%',#{city},'%') escape '/'</if>
        group by tcl.end_customers
    </select>

    <select id="getAgentTargetProgressList" parameterType="com.ruoyi.project.business.domain.vo.board.AgentCompleteOrder"
            resultType="com.ruoyi.project.business.domain.vo.board.AgentTargetProgressVo">
        select
            tcl.agent_id as agentId,
            tcl.area_id AS areaId,
            tcl.country_id AS countryId,
            tcl.city,
            max( tba.area_name ) AS areaName,
            max( c.country_name ) AS countryName,
            sum(tat.target_elevator_count) as targetElevatorCount,
            max(ta.agent_level) as agentLevel
        from tq_contract_lift as tcl
                 left join tb_agent_target as tat on tcl.agent_id = tat.agent_id and tat.del_flag = '0' and  DATE_FORMAT(tat.target_year, '%Y') = #{yearParam}
                 left join tb_agent as ta on ta.agent_id = tcl.agent_id and ta.del_flag = '0'
                 LEFT JOIN tb_area tba ON tcl.area_id = tba.area_id
                 LEFT JOIN tb_country c ON tcl.country_id = c.country_id
        where DATE_FORMAT(tcl.create_time, '%Y') = #{yearParam}
        GROUP BY
            tcl.agent_id,
            tcl.area_id,
            tcl.country_id,
            tcl.city
    </select>
    <select id="getAgentTargetProgressListSub" parameterType="com.ruoyi.project.business.domain.vo.board.AgentTargetProgressVo"
            resultType="com.ruoyi.project.business.domain.vo.board.AgentTargetProgressVo">
        select sum(count) as shippedQty,(sum(count) / #{targetElevatorCount} * 100) as targetCompletionRate,'1' as week
        from tq_contract_lift
        where DATE_FORMAT(create_time, '%Y') = #{yearParam}
          and agent_id = #{agentId}
        group by WEEK(actual_delivery_date,6)
    </select>
</mapper>