<?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="cn.com.ty.lift.business.maintenance.dao.mapper.MaintenanceRecordMapper">
    <resultMap id="BaseResultMap" type="cn.com.ty.lift.business.maintenance.dao.entity.model.response.MtRecordResponse">
        <id column="id" property="id" jdbcType="BIGINT"/>
        <result column="mt_plan_id" property="mtPlanId" jdbcType="BIGINT"/>
        <result column="lift_id" property="liftId" jdbcType="BIGINT"/>
        <result column="project_id" property="projectId" jdbcType="BIGINT"/>
        <result column="mt_company_id" property="mtCompanyId" jdbcType="BIGINT"/>
        <result column="worker_id" property="workerId" jdbcType="BIGINT"/>
        <result column="code" property="code" jdbcType="CHAR"/>
        <result column="lift_type" property="liftType" jdbcType="TINYINT"/>
        <result column="type" property="type" jdbcType="TINYINT"/>
        <result column="plan_date" property="planDate" jdbcType="TIMESTAMP"/>
        <result column="work_date" property="workDate" jdbcType="TIMESTAMP"/>
        <result column="stop_date" property="stopDate" jdbcType="TIMESTAMP"/>
        <result column="recovery_date" property="recoveryDate" jdbcType="TIMESTAMP"/>
        <result column="maintenance_advice" property="maintenanceAdvice" jdbcType="VARCHAR"/>
        <result column="maintenance_option" property="maintenanceOption" jdbcType="LONGVARCHAR"/>
        <result column="position" property="position" jdbcType="VARCHAR"/>
        <result column="status" property="status" jdbcType="TINYINT"/>
        <result column="is_regular" property="isRegular" jdbcType="TINYINT"/>
        <result column="creator_id" property="creatorId" jdbcType="BIGINT"/>
        <result column="create_date" property="createDate" jdbcType="TIMESTAMP"/>
        <result column="worker_id1" property="workerId1" jdbcType="BIGINT"/>
        <result column="is_repair" property="isRepair" jdbcType="TINYINT"/>
        <result column="repair_reason" property="repairReason" jdbcType="VARCHAR"/>
        <result column="signature_img1" property="signatureImg1" jdbcType="VARCHAR"/>
        <result column="signature_img2" property="signatureImg2" jdbcType="VARCHAR"/>
        <result column="sparepart" property="sparepart" jdbcType="LONGVARCHAR"/>
        <result column="parts_cost" property="partsCost" jdbcType="DECIMAL"/>
        <result column="man_cost" property="manCost" jdbcType="DECIMAL"/>
        <result column="safety_confirm" property="safetyConfirm" jdbcType="VARCHAR"/>
        <result column="has_evaluate" property="hasEvaluate" jdbcType="INTEGER"/>

        <result column="project_name" property="projectName" jdbcType="VARCHAR"/>
        <result column="project_code" property="projectCode" jdbcType="VARCHAR"/>
        <result column="address" property="projectAddress" jdbcType="VARCHAR"/>
        <result column="use_company_code" property="useCompanyCode" jdbcType="VARCHAR"/>
        <result column="mt_company_name" property="mtCompanyName" jdbcType="VARCHAR"/>
        <result column="category" property="category" jdbcType="INTEGER"/>
        <result column="registration_code" property="registrationCode" jdbcType="VARCHAR"/>
        <result column="worker_name" property="workerName" jdbcType="VARCHAR"/>
        <result column="worker_mobile" property="workerMobile" jdbcType="VARCHAR"/>
        <result column="maintenance_advice" property="maintenanceAdvice" jdbcType="VARCHAR"/>
        <result column="repair_diff" property="repairDiff" jdbcType="INTEGER"/>
        <result column="star_level" property="starLevel" jdbcType="INTEGER"/>
        <result column="device_position" property="devicePosition" jdbcType="VARCHAR"/>
    </resultMap>

    <sql id="Base_Column_List">
		id, mt_plan_id, lift_id, project_id, mt_company_id, worker_id, code, lift_type, type, 
		plan_date, work_date, stop_date, recovery_date, maintenance_advice, maintenance_option, position, status,
		is_regular, creator_id, create_date, worker_id1, is_repair, repair_reason, signature_img1, 
		signature_img2, sparepart, parts_cost, man_cost, safety_confirm
	</sql>

    <!--根据公司id和电梯id项目名称、项目id、电梯位置 -->
    <select id="findProjectByCompanyId"
            resultType="cn.com.ty.lift.business.maintenance.dao.entity.model.response.MaintenanceRecordResponse"
            parameterType="cn.com.ty.lift.business.maintenance.dao.entity.model.request.MaintenanceRecordRequest">
        SELECT l.id AS liftId,
        l.device_position AS devicePosition,
        p.project_name AS projectName,
        p.id AS projectId
        FROM project_lift_relevance plr
        LEFT JOIN project p ON plr.project_id = p.id
        LEFT JOIN lift l ON plr.lift_id = l.id
        WHERE 1 = 1
        <if test="request.mtCompanyId!=null and request.mtCompanyId!=''">
            AND plr.mt_company_id = #{request.mtCompanyId,jdbcType=BIGINT}
        </if>
        <if test="request.liftId!=null and request.liftId!=''">
            AND plr.lift_id = #{request.liftId,jdbcType=BIGINT}
        </if>
    </select>

    <!--根据公司id和电梯id获取上次保养信息 -->
    <select id="findRecordByCompanyId"
            resultType="cn.com.ty.lift.business.maintenance.dao.entity.model.response.MaintenanceRecordResponse"
            parameterType="cn.com.ty.lift.business.maintenance.dao.entity.model.request.MaintenanceRecordRequest">
        SELECT mt_plan_id AS mtPlanId,
               work_date AS workDate,
               type AS type,
               lift_id AS liftId
        FROM maintenance_record
        WHERE 1=1
        <if test="request.mtCompanyId!=null and request.mtCompanyId!=''">
            AND mt_company_id = #{request.mtCompanyId,jdbcType=BIGINT}
        </if>
        <if test="request.liftId!=null and request.liftId!=''">
            AND lift_id = #{request.liftId,jdbcType=BIGINT}
        </if>
        AND work_date = (SELECT max(work_date)
        FROM maintenance_record
        WHERE status > 1
        <if test="request.mtCompanyId!=null and request.mtCompanyId!=''">
            AND mt_company_id = #{request.mtCompanyId,jdbcType=BIGINT}
        </if>
        <if test="request.liftId!=null and request.liftId!=''">
            AND lift_id = #{request.liftId,jdbcType=BIGINT}
        </if>)
    </select>

	<!--app端 保养任务列表 (1:保养中、2:已完成) -->
	<select id="findRecordByWorkerId" resultType="cn.com.ty.lift.business.maintenance.dao.entity.model.response.MaintenanceAppResponse"
			parameterType="cn.com.ty.lift.business.maintenance.dao.entity.model.request.MaintenanceRecordRequest">
		SELECT DISTINCT p.project_name AS projectName,
			p.id                AS projectId,
			mr.id               AS mtPlanId,
			mr.id               AS recordId,
			l.id                AS liftId,
			l.coordinate        AS coordinate,
			l.registration_code AS registrationCode,
			l.use_company_code  AS useCompanyCode,
			l.lift_type         AS liftType,
			l.category          AS category,
			l.lift_code         AS liftCode,
			l.device_position   AS devicePosition,
			ui.name             AS workerName,
			mr.worker_id        AS workerId,
		    mr.worker_id1       AS workerId1,
			mr.plan_date        AS planDate,
			mr.type             AS maintenanceType,
			mr.status           AS status,
		    mr.has_evaluate     AS hasEvaluate
		FROM maintenance_record mr
		LEFT JOIN project p ON mr.project_id = p.id
        <if test="request.currentRoleCode == 'REGION_DIRECTOR' or request.currentRoleCode == 'CLERK' or request.look == 1 ">
            LEFT JOIN project_user pu ON p.id = pu.project_id
        </if>
		LEFT JOIN lift l ON mr.lift_id = l.id
		LEFT JOIN user_info ui ON mr.worker_id = ui.user_id
		WHERE mr.mt_company_id = #{request.mtCompanyId,jdbcType=BIGINT}
        <choose>
            <when test="request.currentRoleCode == 'REGION_DIRECTOR' or request.currentRoleCode == 'CLERK' or request.look == 1 ">
                AND pu.user_id = #{request.userId,jdbcType=BIGINT}
            </when>
            <when test="request.userId !=null">
                AND mr.worker_id1 = #{request.userId,jdbcType=BIGINT}
            </when>
            <otherwise/>
        </choose>
		<if test="request.status!=null and request.status!=''">
			AND mr.status = #{request.status,jdbcType=VARCHAR}
		</if>
        <if test="request.currentTime!=null">
            AND <![CDATA[ date_format(mr.work_date, '%Y-%m-%d') = #{request.currentTime}]]>
        </if>
        <if test="request.beginTime!=null">
            AND <![CDATA[ date_format(mr.work_date, '%Y-%m-%d') >= #{request.beginTime}]]>
        </if>
        <if test="request.endTime!=null">
            AND <![CDATA[ date_format(mr.work_date, '%Y-%m-%d') <= #{request.endTime}]]>
        </if>
	</select>

    <!--app端 保养任务统计 (1:保养中、2:已完成) -->
    <select id="countRecordByWorkerId" resultType="cn.com.ty.lift.business.maintenance.dao.entity.model.MaintenanceCount"
            parameterType="cn.com.ty.lift.business.maintenance.dao.entity.model.request.MaintenanceRecordRequest">
        SELECT  t.planDate,
                MAX(CASE t.status WHEN '1' THEN t.total ELSE 0 END) inProgress,
                MAX(CASE t.status WHEN '2' THEN t.total ELSE 0 END) complete
        FROM (
            SELECT mr.status,
                 date_format(mr.work_date, '%Y-%m-%d') as planDate,
                 count(1) total
        FROM maintenance_record mr
                LEFT JOIN project p ON mr.project_id = p.id
                <if test="request.currentRoleCode == 'REGION_DIRECTOR' or request.currentRoleCode == 'CLERK' or request.look == 1 ">
                    LEFT JOIN project_user pu ON p.id = pu.project_id
                </if>
                LEFT JOIN lift l ON mr.lift_id = l.id
                LEFT JOIN user_info ui ON mr.worker_id = ui.user_id
        WHERE mr.mt_company_id = #{request.mtCompanyId,jdbcType=BIGINT}
        <choose>
            <when test="request.currentRoleCode == 'REGION_DIRECTOR' or request.currentRoleCode == 'CLERK' or request.look == 1 ">
                AND pu.user_id = #{request.userId,jdbcType=BIGINT}
            </when>
            <when test="request.userId !=null">
                AND mr.worker_id1 = #{request.userId,jdbcType=BIGINT}
            </when>
            <otherwise/>
        </choose>
        <if test="request.beginTime!=null">
            AND <![CDATA[ date_format(mr.work_date, '%Y-%m-%d') >= #{request.beginTime}]]>
        </if>
        <if test="request.endTime!=null">
            AND <![CDATA[ date_format(mr.work_date, '%Y-%m-%d') <= #{request.endTime}]]>
        </if>
        GROUP BY planDate,
        status
        ) t
        GROUP BY t.planDate
    </select>

    <select id="findRecordByLiftId"
            resultType="cn.com.ty.lift.business.maintenance.dao.entity.model.response.ScanRecordResponse"
            parameterType="cn.com.ty.lift.business.maintenance.dao.entity.model.request.MtRecordRequest">
        SELECT mr.id               AS id,
               l.id                AS liftId,
               l.registration_code AS registrationCode,
               p.project_name      AS projectName,
               l.device_position   AS devicePosition,
               l.lift_type         AS liftType,
               ui.name             AS workerName
        FROM maintenance_record mr
             LEFT JOIN lift l ON l.id = mr.lift_id
             LEFT JOIN project p ON mr.project_id = p.id
             LEFT JOIN user_info ui ON mr.worker_id = ui.user_id
        WHERE mr.lift_id = #{request.liftId,jdbcType=BIGINT} AND mr.status = '2'
    </select>

    <!--日常保养-保养单：根据条件分页查询-->
    <select id="pageRecordByCondition" resultMap="BaseResultMap"
            parameterType="cn.com.ty.lift.business.maintenance.dao.entity.model.request.MtRecordRequest">
        SELECT
        mr.*,
        li.use_company_code,
        li.registration_code,
        li.category,
        ui.`name` AS worker_name,
        pr.project_name,
        ifnull(ev.star_level, 0),
        TimeStampDiff(MINUTE ,mr.stop_date,mr.recovery_date) AS repair_diff
        FROM
        maintenance_record mr
        LEFT JOIN lift li ON mr.lift_id = li.id
        LEFT JOIN user_info ui ON mr.worker_id1 = ui.user_id
        LEFT JOIN project pr ON mr.project_id = pr.id AND pr.mt_company_id = mr.mt_company_id
        LEFT JOIN evaluation ev ON mr.id = ev.record_id
        LEFT JOIN region r ON pr.region_id = r.id
        WHERE ((status = '2' AND has_evaluate = '0') or (status = '2' AND has_evaluate = '1'))
            <if test="cond.mtCompanyId != null and cond.mtCompanyId > 0">
                AND mr.mt_company_id = #{cond.mtCompanyId}
            </if>
            <if test="cond.regionId != null and cond.regionId > 0">
                AND pr.region_id = #{cond.regionId}
            </if>
            <if test="cond.projectId != null and cond.projectId > 0">
                AND pr.id = #{cond.projectId}
            </if>
            <if test="cond.areaDirectorId != null and cond.areaDirectorId > 0">
                AND r.user_id = #{cond.areaDirectorId}
            </if>
            <if test="cond.workerId != null and cond.workerId > 0">
                AND mr.worker_id1 = #{cond.workerId}
            </if>
            <if test="cond.planBegin != null">
                AND mr.plan_date &gt; #{cond.planBegin}
            </if>
            <if test="cond.planEnd != null">
                AND mr.plan_date &lt; #{cond.planEnd}
            </if>
            <if test="cond.workDate != null">
                AND mr.work_date = #{cond.workDate}
            </if>
            <if test="cond.liftCodeQuery != null and cond.liftCodeQuery != ''">
                AND li.registration_code like '%${liftCodeQuery}%'
                OR li.custom_number like '%${liftCodeQuery}%'
            </if>
    </select>

    <!--日常保养-保养单：根据条件汇总条数-->
    <select id="countRecordByCondition" resultType="java.lang.Long"
            parameterType="cn.com.ty.lift.business.maintenance.dao.entity.model.request.MtRecordRequest">
        SELECT
        count(1)
        FROM
        maintenance_record mr
        WHERE  ((status = '2' AND has_evaluate = '0') or (status = '2' AND has_evaluate = '1'))
            <if test="cond.mtCompanyId != null and cond.mtCompanyId > 0">
                AND mr.mt_company_id = #{cond.mtCompanyId}
            </if>
    </select>

    <!--日常保养-保养单：根据id查询,带关联信息-->
    <select id="infoById" resultMap="BaseResultMap"
            parameterType="cn.com.ty.lift.business.maintenance.dao.entity.model.request.MtRecordRequest">
        SELECT DISTINCT
        mr.*,
        li.use_company_code,
        li.registration_code,
        li.device_position,
        li.category,
        mc.name AS mt_company_name,
        ui.`name` AS worker_name,
        ui.mobile AS worker_mobile,
        pr.project_name,
        pr.project_code,
        mr.maintenance_advice,
        pr.address,
        ev.star_level,
        li.device_position,
        case li.category
            when 1 then '曳引梯'
            when 2 then '液压梯'
            when 3 then '杂物梯'
            when 4 then '自动扶梯'
            when 5 then '自动人行道'
            else '其他' end categoryStr,
        case mr.type
            when 1 then '半月保'
            when 2 then '季度保'
            when 3 then '半年保'
            when 4 then '全年保'
            else '其他' end AS typeStr,
        if(has_evaluate = 1,'已评价','未评价') AS hasEvaluateStr,
        TimeStampDiff(MINUTE ,mr.stop_date,mr.recovery_date) AS repair_diff
        FROM
        maintenance_record mr
        LEFT JOIN lift li ON mr.lift_id = li.id
        LEFT JOIN user_info ui ON mr.worker_id1 = ui.user_id
        LEFT JOIN project pr ON mr.project_id = pr.id AND mr.mt_company_id = pr.mt_company_id
        LEFT JOIN evaluation ev ON mr.id = ev.record_id AND ev.source = 1
        LEFT JOIN maintenance_company mc ON mr.mt_company_id = mc.id
        <where>
            <if test="cond.id != null and cond.id > 0">
                mr.id = #{cond.id}
            </if>
        </where>
    </select>

    <!--日常保养-保养单：根据ids查询,带关联信息-->
    <select id="listByIds" resultMap="BaseResultMap"
            parameterType="cn.com.ty.lift.business.maintenance.dao.entity.model.request.MtRecordRequest">
        SELECT
        mr.*,
        li.use_company_code,
        li.registration_code,
        li.category,
        mc.name AS mt_company_name,
        ui.`name` AS worker_name,
        pr.project_name,
        pr.project_code,
        ev.star_level
        FROM
        maintenance_record mr
        LEFT JOIN lift li ON mr.lift_id = li.id
        LEFT JOIN user_info ui ON mr.worker_id1 = ui.user_id
        LEFT JOIN project pr ON mr.project_id = pr.id AND mr.mt_company_id = pr.mt_company_id
        LEFT JOIN evaluation ev ON mr.id = ev.record_id AND ev.source = 1
        LEFT JOIN maintenance_company mc ON mr.mt_company_id = mc.id
        <where>
            <if test="cond.id != null and cond.id > 0">
                mr.id = #{cond.id}
            </if>
        </where>
    </select>

    <select id="pageByLift" resultMap="BaseResultMap"
            parameterType="cn.com.ty.lift.business.maintenance.dao.entity.model.request.MtRecordRequest">
        SELECT
        mr.*,
        li.use_company_code,
        li.registration_code,
        li.category,
        mc.name AS mt_company_name,
        ui.`name` AS worker_name,
        pr.project_name,
        pr.project_code,
        ev.star_level
        FROM
        maintenance_record mr
        LEFT JOIN lift li ON mr.lift_id = li.id
        LEFT JOIN user_info ui ON mr.worker_id1 = ui.user_id
        LEFT JOIN project pr ON mr.project_id = pr.id
        LEFT JOIN evaluation ev ON mr.id = ev.record_id
        LEFT JOIN maintenance_company mc ON mr.mt_company_id = mc.id
        <where>
            <if test="cond.liftId != null and cond.liftId > 0">
                AND mr.lift_id = #{cond.liftId}
            </if>
            <if test="cond.projectId != null and cond.projectId > 0">
                AND mr.project_id = #{cond.projectId}
            </if>
            <if test="cond.mtCompanyId != null and cond.mtCompanyId > 0">
                AND mr.mt_company_id = #{cond.mtCompanyId}
            </if>
        </where>
    </select>

    <select id="queryMaintenanceTask" parameterType="java.lang.Long" resultType="cn.com.ty.lift.business.maintenance.dao.third.MaintenanceTask">
        SELECT mr.id,
               CASE mr.type
                   WHEN '1' THEN '半月'
                   WHEN '2' THEN '季度'
                   WHEN '3' THEN '半年'
                   WHEN '4' THEN '全年'
                   END AS type,
               lc.code,
               mr.maintenance_option,
               mr.signature_img1,
               mr.maintenance_advice
        FROM maintenance_record mr
                 LEFT JOIN lift_certificate lc ON mr.worker_id1 = lc.owner_id
        WHERE mr.mt_company_id = #{mtCompanyId}
          AND mr.lift_id = #{liftId}
          AND plan_date = current_date()
    </select>
</mapper>