<?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.quotation.TqQuotationMapper">

    <resultMap type="TqQuotation" id="TqQuotationResult">
        <result property="id" column="id"/>
        <result property="quotationNo" column="quotation_no"/>
        <result property="version" column="version"/>
        <result property="agentId" column="agent_id"/>
        <result property="projectId" column="project_id"/>
        <result property="currencyId" column="currency_id"/>
        <result property="exchangeRate" column="exchange_rate"/>
        <result property="price" column="price"/>
        <result property="finalPrice" column="final_price"/>
        <result property="freightPrice" column="freight_price"/>
        <result property="basicPrice" column="basic_price"/>
        <result property="optionalPrice" column="optional_price"/>
        <result property="quotationStatus" column="quotation_status"/>
        <result property="submitTime" column="submit_time"/>
        <result property="orderTime" column="order_time"/>
        <result property="systemCheckResult" column="system_check_result"/>
        <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="quotationVersion" column="quotation_version"/>
    </resultMap>

    <resultMap type="com.ruoyi.project.business.domain.vo.quotation.QuotationVO" id="TqQuotationVOResult">
        <result property="id" column="id"/>
        <result property="quotationNo" column="quotation_no"/>
        <result property="version" column="version"/>
        <result property="currencyId" column="currency_id"/>
        <result property="currencyName" column="currency_name"/>
        <result property="finalPrice" column="final_price"/>
        <result property="createBy" column="create_by"/>
        <result property="createTime" column="create_time"/>
        <result property="submitTime" column="submit_time"/>
        <result property="quotationStatus" column="quotation_status"/>
        <result property="projectNo" column="project_no"/>
        <result property="projectName" column="project_name"/>
        <result property="type" column="type"/>
        <result property="segmentedMarket" column="segmented_market"/>
        <result property="countryId" column="country_id"/>
        <result property="city" column="city"/>
        <result property="nickName" column="nick_name"/>
        <result property="additionalFees" column="additional_fees"/>
        <result property="elevatorModel" column="elevator_model"/>
        <result property="exchangeRate" column="exchange_rate"/>
        <result property="price" column="price"/>
        <result property="quotationVersion" column="quotation_version"/>

        <result property="quotationStatusName" column="quotationStatusName"/>
        <result property="countryName" column="country_name"/>
    </resultMap>

    <sql id="selectTqQuotationVo">
        select id,
               quotation_no,
               version,
               agent_id,
               project_id,
               currency_id,
               exchange_rate,
               price,
               final_price,
               freight_price,
               basic_price,
               optional_price,
               quotation_status,
               quotation_version,
               submit_time,
               order_time,
               system_check_result,
               permission_char,
               del_flag,
               create_time,
               create_by,
               update_time,
               update_by,
               remark
        from tq_quotation
    </sql>

    <select id="selectTqQuotationList" resultMap="TqQuotationVOResult">
        SELECT
        quo.id,
        quo.quotation_no,
        quo.version,
        quo.currency_id,
        quo.create_by,
        quo.freight_price as "additional_cost",
        quo.price,
        quo.final_price,
        quo.final_currency_price,
        quo.submit_time,
        quo.exchange_rate,
        quo.quotation_status,
        quo.quotation_version,
        project.project_no,
        project.project_name,
        project.type,
        project.segmented_market,
        project.country_id,
        cty.country_name,
        project.city,
        tc.currency_name,
        u.nick_name,
        t.sumFees as additional_fees,
        (SELECT GROUP_CONCAT(DISTINCT tem.elevator_model) FROM tq_specification ts
        LEFT JOIN tp_elevator_model tem on tem.id = ts.elevator_model_id
        WHERE ts.quotation_id = quo.id and ts.del_flag = '0') as elevator_model
        FROM tq_quotation quo
        left join (
            select ts.quotation_id,
            (sum( IFNULL(tss.land_ship_fees,0) )+ sum( IFNULL(tss.sea_ship_fees,0) )+
             sum( IFNULL(tss.commission_fees,0) )+ sum( IFNULL(tss.other_fees,0))) AS sumFees
            FROM tq_specification_surcharge as tss
            left join tq_specification as ts on ts.id = tss.specification_id and ts.del_flag = '0'
            where tss.del_flag = '0' and ts.quotation_id is not null
            group by ts.quotation_id
        ) as t on quo.id = t.quotation_id
        LEFT JOIN tc_project project on quo.project_id = project.project_id
        LEFT JOIN tb_currency tc on quo.currency_id = tc.currency_id
        LEFT JOIN tb_country cty on project.country_id = cty.country_id
        LEFT JOIN sys_user u on quo.create_by = u.user_id
        inner join (SELECT p.premession_char FROM (SELECT @premessionStr:= #{permissionChar} p) param ,
        getpremessionview_chars p
        ) permission on permission.premession_char = quo.permission_char
        <where>
            <if test="projectId != null">
                and quo.project_id = #{projectId}
            </if>
            <if test="quotationNo != null  and quotationNo != ''">
                and quo.quotation_no like concat('%',#{quotationNo},'%')
            </if>
            <if test="excludeQuotationIdList != null and excludeQuotationIdList.size() > 0">
                and quo.id not in
                <foreach item="item" collection="excludeQuotationIdList" open="(" separator="," close=")">
                    #{item}
                </foreach>
            </if>
            <if test="quotationNoList != null and quotationNoList.size() > 0">
                and quo.quotation_no in
                <foreach item="item" collection="quotationNoList" open="(" separator="," close=")">
                    #{item}
                </foreach>
            </if>
            <if test="beginTime != null and endTime != null">and quo.submit_time between #{beginTime} and #{endTime}
            </if>
            <if test="areaIdList != null and areaIdList.size() > 0">
                and quo.area_id in
                <foreach item="item" collection="areaIdList" open="(" separator="," close=")">
                    #{item}
                </foreach>
            </if>
            <if test="projectName != null  and projectName != ''">and project.project_name like
                concat('%',#{projectName},'%')
            </if>
            <if test="type != null and type.size() > 0">
                and project.type in
                <foreach item="item" collection="type" open="(" separator="," close=")">
                    #{item}
                </foreach>
            </if>
            <if test="segmentedMarket != null and segmentedMarket.size() > 0">
                and project.segmented_market in
                <foreach item="item" collection="segmentedMarket" open="(" separator="," close=")">
                    #{item}
                </foreach>
            </if>
            <if test="countryId != null and countryId.size() > 0">
                and project.country_id in
                <foreach item="item" collection="countryId" open="(" separator="," close=")">
                    #{item}
                </foreach>
            </if>
            <if test="city != null  and city != ''">and project.city like concat('%',#{city},'%')</if>
            <if test="currencyId != null and currencyId.size() > 0">
                and quo.currency_id in
                <foreach item="item" collection="currencyId" open="(" separator="," close=")">
                    #{item}
                </foreach>
            </if>
            <if test="nickName != null  and nickName != ''">and u.nick_name like concat('%',#{nickName},'%')</if>

            <if test="quotationStatus != null and quotationStatus.size() > 0">
                and quo.quotation_status in
                <foreach item="item" collection="quotationStatus" open="(" separator="," close=")">
                    #{item}
                </foreach>
            </if>
            <if test="loginUserId != null  and loginUserId != ''">
                and (quo.permission_char &lt;&gt; #{permission} or quo.create_by = #{loginUserId})
            </if>
        </where>
        <trim prefix="HAVING" prefixOverrides="AND">
            <if test="isGroupBy">
                AND quo.id in (SELECT MAX(tq.id) as id FROM tq_quotation tq
                LEFT JOIN sys_user u on tq.create_by = u.user_id
                inner join (SELECT p.premession_char FROM (SELECT @premessionStr:= #{permissionChar} p) param ,
                getpremessionview_chars p
                ) permission on permission.premession_char = tq.permission_char
                <where>
                    <if test="loginUserId != null  and loginUserId != ''">
                        and (tq.permission_char &lt;&gt; #{permission} or tq.create_by = #{loginUserId})
                    </if>
                    <if test="beginTime != null and endTime != null">and tq.submit_time between #{beginTime} and #{endTime}
                    </if>
                    <if test="elevatorModel != null  and elevatorModel != ''">
                        AND tq.elevator_model like concat('%',#{elevatorModel},'%')
                    </if>
                    <if test="nickName != null  and nickName != ''">and u.nick_name like concat('%',#{nickName},'%')</if>
                    <if test="quotationStatus != null and quotationStatus.size() > 0">
                        and  tq.quotation_status in
                        <foreach item="item" collection="quotationStatus" open="(" separator="," close=")">
                            #{item}
                        </foreach>
                    </if>
                </where>
                GROUP BY quotation_no)
            </if>
            <if test="elevatorModel != null  and elevatorModel != ''">
                AND elevator_model like concat('%',#{elevatorModel},'%')
            </if>
        </trim>
        order by id desc
    </select>

    <select id="selectTqQuotationById" parameterType="Long" resultMap="TqQuotationResult">
        <include refid="selectTqQuotationVo"/>
        where id = #{id}
    </select>

    <select id="selectDetailById" parameterType="Long"
        resultType="com.ruoyi.project.business.domain.vo.quotation.QuotationDetailVO">
        select quo.quotation_no as quotationNo,
               quo.version,
               quo.project_id   as projectId,
               quo.create_by    as createBy,
               quo.agent_id     as agentId,
               quo.currency_id  as currencyId,
               su.nick_name     as quoter,
               quo.update_time  as updateTime,
               quo.quotation_status as quotationStatus,
               quo.discount_flag as discountFlag,
                 quo.quotation_version as quotationVersion
        FROM tq_quotation quo
                 left join sys_user su on quo.create_by = su.user_id
        where id = #{id}
    </select>

    <insert id="insertTqQuotation" parameterType="TqQuotation" useGeneratedKeys="true" keyProperty="id">
        insert into tq_quotation
        <trim prefix="(" suffix=")" suffixOverrides=",">
            <if test="quotationNo != null">quotation_no,</if>
            <if test="version != null">version,</if>
            <if test="agentId != null">agent_id,</if>
            <if test="projectId != null">project_id,</if>
            <if test="currencyId != null">currency_id,</if>
            <if test="exchangeRate != null">exchange_rate,</if>
            <if test="price != null">price,</if>
            <if test="finalPrice != null">final_price,</if>
            <if test="freightPrice != null">freight_price,</if>
            <if test="basicPrice != null">basic_price,</if>
            <if test="optionalPrice != null">optional_price,</if>
            <if test="quotationStatus != null">quotation_status,</if>
            <if test="submitTime != null">submit_time,</if>
            <if test="orderTime != null">order_time,</if>
            <if test="systemCheckResult != null">system_check_result,</if>
            <if test="permissionChar != null and permissionChar != ''">permission_char,</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="areaId != null">area_id,</if>
            <if test="discountFlag != null">discount_flag,</if>
            <if test="agentDiscountRate != null">agent_discount_rate,</if>
            <if test="countryDiscountRate != null">country_discount_rate,</if>
            <if test="quotationVersion != null">quotation_version,</if>

        </trim>
        <trim prefix="values (" suffix=")" suffixOverrides=",">
            <if test="quotationNo != null">#{quotationNo},</if>
            <if test="version != null">#{version},</if>
            <if test="agentId != null">#{agentId},</if>
            <if test="projectId != null">#{projectId},</if>
            <if test="currencyId != null">#{currencyId},</if>
            <if test="exchangeRate != null">#{exchangeRate},</if>
            <if test="price != null">#{price},</if>
            <if test="finalPrice != null">#{finalPrice},</if>
            <if test="freightPrice != null">#{freightPrice},</if>
            <if test="basicPrice != null">#{basicPrice},</if>
            <if test="optionalPrice != null">#{optionalPrice},</if>
            <if test="quotationStatus != null">#{quotationStatus},</if>
            <if test="submitTime != null">#{submitTime},</if>
            <if test="orderTime != null">#{orderTime},</if>
            <if test="systemCheckResult != null">#{systemCheckResult},</if>
            <if test="permissionChar != null and permissionChar != ''">#{permissionChar},</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="areaId != null">#{areaId},</if>
            <if test="discountFlag != null">#{discountFlag},</if>
            <if test="agentDiscountRate != null">#{agentDiscountRate},</if>
            <if test="countryDiscountRate != null">#{countryDiscountRate},</if>
            <if test="quotationVersion != null">#{quotationVersion},</if>
        </trim>
    </insert>

    <update id="updateTqQuotation" parameterType="TqQuotation">
        update tq_quotation
        <trim prefix="SET" suffixOverrides=",">
            <if test="quotationNo != null">quotation_no = #{quotationNo},</if>
            <if test="version != null">version = #{version},</if>
            <if test="agentId != null">agent_id = #{agentId},</if>
            <if test="projectId != null">project_id = #{projectId},</if>
            <if test="currencyId != null">currency_id = #{currencyId},</if>
            <if test="exchangeRate != null">exchange_rate = #{exchangeRate},</if>
            <if test="price != null">price = #{price},</if>
            <if test="finalPrice != null">final_price = #{finalPrice},</if>
            <if test="freightPrice != null">freight_price = #{freightPrice},</if>
            <if test="basicPrice != null">basic_price = #{basicPrice},</if>
            <if test="optionalPrice != null">optional_price = #{optionalPrice},</if>
            <if test="quotationStatus != null">quotation_status = #{quotationStatus},</if>
            <if test="submitTime != null">submit_time = #{submitTime},</if>
            <if test="orderTime != null">order_time = #{orderTime},</if>
            <if test="systemCheckResult != null">system_check_result = #{systemCheckResult},</if>
            <if test="permissionChar != null and permissionChar != ''">permission_char = #{permissionChar},</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="quotationVersion != null">quotation_version = #{quotationVersion},</if>
        </trim>
        where id = #{id}
    </update>
    <update id="updateAuditOptionalPrice">
        update tq_quotation
        set optional_price   = optional_price + #{price},
            price            = price + #{price},
            quotation_status = 5
        where id = #{id}
    </update>

    <delete id="deleteTqQuotationById" parameterType="Long">
        delete
        from tq_quotation
        where id = #{id}
    </delete>

    <delete id="deleteTqQuotationByIds" parameterType="String">
        delete from tq_quotation where id in
        <foreach item="id" collection="array" open="(" separator="," close=")">
            #{id}
        </foreach>
    </delete>

    <select id="getMaxVersionById" resultType="com.ruoyi.project.business.domain.vo.quotation.QuotationVersionVO">
        SELECT max(version) as version,quotation_no FROM tq_quotation WHERE quotation_no in (
        SELECT DISTINCT quotation_no FROM tq_quotation WHERE id in
        <foreach item="id" collection="list" open="(" separator="," close=")">
            #{id}
        </foreach>
        )
        GROUP BY quotation_no
    </select>

    <select id="listByProjectId" resultMap="TqQuotationVOResult">
        select q.id, q.quotation_no, q.version, p.project_name,q.quotation_version
        from tq_quotation q
                 left join tc_project p on q.project_id = p.project_id
        where q.project_id = #{projectId}
          and q.del_flag = '0'
        order by q.id desc
    </select>

    <select id="getAreaIdByProjectId" resultType="java.lang.Long">
        SELECT tc.area_id
        FROM tc_project tc
        WHERE tc.del_flag = '0'
          and tc.project_id = #{projectId}
    </select>
    <select id="listPendingApproval"
        resultType="com.ruoyi.project.business.domain.vo.quotation.QuotationApprovalVO">
        SELECT DISTINCT tq.id,
                        tp.project_name as projectName,
                        tq.price,
                        tp.city,
                        tc.country_name as countryName,
                        (SELECT tbp.bargain_price
                         FROM tq_bargain_price tbp
                         WHERE tbp.quotation_id = tq.id
                         ORDER BY tbp.id DESC
                         LIMIT 1)       AS bargainPrice,
                        u.nick_name     as nickName,
                        dict.remark as currencyName
        FROM tq_quotation tq
                 LEFT JOIN tc_project tp ON tq.project_id = tp.project_id
                 LEFT JOIN sys_user u ON tq.create_by = u.user_id
                 LEFT JOIN tb_country tc ON tc.country_id = tp.country_id
                 LEFT JOIN flow f ON f.business_id = tq.id
                 LEFT JOIN flow_task ft ON ft.flow_id = f.id
                 LEFT JOIN flow_task_user ftu ON ftu.task_id = ft.id
                 LEFT JOIN sys_dict_data dict ON dict.dict_type = 'currency_type' and tq.currency_id = dict.dict_value
        WHERE tq.quotation_status = 7
          AND ftu.audit_user = #{userId}
          AND f.audit_flow = 2
          AND ftu.`status` = 100
        order by id desc
    </select>
    <select id="detailApproval"
        resultType="com.ruoyi.project.business.domain.vo.quotation.H5QuotationDetailVO">
        SELECT tp.city,
               tc.country_name                                                as countryName,
               u1.nick_name                                                   as quoter,
               (case when tq.agent_id = 0 then '总部' else u2.nick_name end)  as saler,
               tp.developer,
               tq.quotation_no                                                as quotationNo,
                tq.quotation_version                                          as quotationVersion,
               tp.project_name                                                as projectName,
               tq.version                                                     as version,
               (case when tq.agent_id = 0 then '总部' else ta.agent_name end) as agentName
        FROM tq_quotation tq
                 LEFT JOIN tc_project tp ON tq.project_id = tp.project_id
                 LEFT JOIN sys_user u1 ON tq.create_by = u1.user_id
                 LEFT JOIN tb_country tc ON tc.country_id = tp.country_id
                 LEFT JOIN tb_agent ta ON tq.agent_id = ta.agent_id
                 LEFT JOIN sys_user u2 ON ta.parent_saler_id = u2.user_id
        WHERE tq.id = #{quotationId}
    </select>

    <select id="listQuotationExport"
        resultType="com.ruoyi.project.business.domain.vo.quotation.QuotationExportVO">
        SELECT
        quo.id as quotationId,
        quo.quotation_no as quotationNo,
        quo.submit_time as submitDate,
        quo.exchange_rate as exchangeRate,
        pro.project_name as projectName,
        pro.email as email,
        pro.address as address,
        acc.account_name as client,
        cur.currency_name as currencyName,
        quo.final_price as finalPrice,
        quo.freight_price as freightPrice,
        quo.original_basic_price as originalBasicPrice,
        quo.original_optional_price as originalOptionalPrice,
        quo.basic_price as basicPrice,
        quo.optional_price as optionalPrice,
        quo.quotation_version as quotationVersion
        FROM
        tq_quotation quo
        LEFT JOIN tc_project pro on pro.project_id = quo.project_id
        LEFT JOIN tc_account acc on pro.account_id = acc.account_id
        LEFT JOIN tb_currency cur on quo.currency_id = cur.currency_id
        WHERE quo.id in
        <foreach item="id" collection="quotationIdList" open="(" separator="," close=")">
            #{id}
        </foreach>
    </select>
</mapper>