<?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.wisenergy.mapper.WorkTimeOrderMapper">

    <!-- 通用查询映射结果 -->
    <resultMap id="BaseResultMap" type="cn.wisenergy.model.app.WorkTimeOrder">
        <id column="work_id" property="workId"/>
        <result column="user_id" property="userId"/>
        <result column="project_id" property="projectId"/>
        <result column="dept_id" property="deptId"/>
        <result column="work_time" property="workTime"/>
        <result column="work_day" property="workDay"/>
        <result column="status" property="status"/>
        <result column="reviewer_id" property="reviewerId"/>
        <result column="des" property="des"/>
        <result column="reason" property="reason"/>
        <result column="type" property="type"/>
        <result column="is_overtime" property="isOvertime"/>
        <result column="reject_time" property="rejectTime"/>
        <result column="create_time" property="createTime"/>
        <result column="modify_time" property="modifyTime"/>
    </resultMap>

    <resultMap id="userWorkTimeStatisticsByProject" type="cn.wisenergy.model.dto.UserWorkTimeStatisticsByProject">
        <result property="userId" column="user_id"/>
        <result property="userName" column="user_name"/>
        <collection property="projectWorkTimeAndType" ofType="cn.wisenergy.model.dto.ProjectWorkTimeAndType">
            <result property="projectId" column="project_id"/>
            <result property="projectType" column="project_type"/>
            <result property="projectName" column="project_name"/>
            <result property="isOvertime" column="is_overtime"/>
            <result property="workTime" column="work_time"/>
        </collection>
    </resultMap>

    <resultMap id="workTimeAndCostCollect" type="cn.wisenergy.model.dto.WorkTimeAndCostCollect" >
        <result property="type" column="type"/>
        <collection property="deptProjectWorkTimeAndCosts" resultMap="deptProjectWorkTimeAndCosts" >
        </collection>
    </resultMap>

    <resultMap id="deptProjectWorkTimeAndCosts" type="cn.wisenergy.model.dto.DeptProjectWorkTimeAndCost">
        <result property="deptId" column="dept_id"/>
        <result property="deptName" column="dept_name"/>
        <collection property="projectWorkTimeAndCostStatistics" ofType="cn.wisenergy.model.dto.ProjectWorkTimeAndCostStatistics">
            <result property="projectId" column="project_id"/>
            <result property="projectName" column="project_name"/>
            <result property="firstTime" column="first_time"/>
            <result property="lastTime" column="last_time"/>
            <result property="totalTime" column="total_time"/>
            <result property="cost" column="cost"/>
        </collection>
    </resultMap>


    <!-- 通用查询结果列 -->
    <sql id="vals">
       #{userId},#{projectId},#{deptId},#{workTime},#{workDay},#{status},#{reviewerId},#{des},#{reason},#{type},#{isOvertime},#{rejectTime},now(),now()
    </sql>
    <sql id="cols_exclude_id">
      user_id, project_id, dept_id, work_time, work_day, status, reviewer_id, des, reason, type, is_overtime,reject_time, create_time, modify_time
    </sql>

    <sql id="criteria">
        <if test="workId != null">and work_id = #{workId}</if>
        <if test="userId != null">and user_id = #{userId}</if>
        <if test="projectId != null">and project_id =#{projectId}</if>
        <if test="deptId != null">and dept_id = #{deptId}</if>
        <if test="workTime != null">and work_time = #{workTime}</if>
        <if test="workDay != null">and work_day = #{workDay}</if>
        <if test=" status != null">and `status` = #{status}</if>
        <if test=" reviewerId != null">and reviewer_id = #{reviewerId}</if>
        <if test="des != null">and des =#{des}</if>
        <if test="reason != null">and reason = #{reason}</if>
        <if test="type != null">and type = #{type}</if>
        <if test="isOvertime != null">and is_overtime = #{isOvertime}</if>
        <if test="createTime != null">and create_time &gt;= #{createTime}</if>
        <if test="modifyTime != null">and #{modifyTime} &gt;= modify_time</if>
    </sql>

    <resultMap id="dayWorkTimeAndType" type="cn.wisenergy.model.dto.DayWorkTimeAndType">
        <result property="userId" column="user_id"/>
        <result property="day" column="day(work_day)"/>
        <result property="type" column="type"/>
        <result property="workTime" column="sum(work_time)"/>
    </resultMap>

    <resultMap id="monthlyWorkHourStatistics" type="cn.wisenergy.model.dto.MonthlyWorkingHoursStatistics">
        <result property="count" column="count(1)"/>
        <result property="workTime" column="sum(work_time)"/>
        <result property="projectType" column="type"/>
    </resultMap>

    <sql id="table">
        work_time_order
    </sql>

    <insert id="save" keyProperty="workId" useGeneratedKeys="true">
        insert into
        <include refid="table"/>
        (<include refid="cols_exclude_id"/>)
        value(
        <include refid="vals"/>
        )
    </insert>


    <update id="updateByIds">
        UPDATE
        <include refid="table"/>
        SET status = 2,reviewer_id = #{reviewerId}
        WHERE work_id IN
        <foreach collection="ids" item="id" open="(" close=")" separator=",">
            #{id}
        </foreach>
    </update>

    <update id="updateStatusById">
        UPDATE
        <include refid="table"/>
        SET status = 3,reason = #{reason},reviewer_id = #{reviewerId},modify_time=now(),reject_time=now()
        WHERE work_id = #{id}

    </update>
    <update id="updateAutoExamine">
        UPDATE
        <include refid="table"/>
        SET status = 5,modify_time=now()
        <where>work_id IN
            <foreach collection="workIds" item="id" open="(" close=")" separator=",">
                #{id}
            </foreach>
        </where>
    </update>


    <select id="getByDay" resultType="cn.wisenergy.model.app.WorkTimeOrder">
        SELECT
        <include refid="Base_Column_List"/>
        FROM
        <include refid="table"/>
        <where>
            <if test="null !=userId">
                <if test="null != userId">
                    AND user_id = #{userId}
                </if>
                <if test="null != workDay">
                    AND DATE_FORMAT(work_day, '%Y%m%d') = DATE_FORMAT(#{workDay} ,'%Y%m%d')
                </if>
            </if>
        </where>

    </select>
    <select id="queryByPage" resultType="cn.wisenergy.model.app.WorkTimeOrder">
        SELECT
        <include refid="Base_Column_List"/>
        FROM
        <include refid="table"/>
        <where>
            <if test="null != projectId">
                AND project_id = #{projectId}
            </if>
            <if test="null != status">
                AND status = #{status}
            </if>
            <if test="null != type">
                AND type = #{type}
            </if>
            <if test="null != type">
                AND dept_id = #{deptId}
            </if>
        </where>
        ORDER BY work_day DESC
    </select>

    <!-- 通用查询结果列 -->
    <sql id="Base_Column_List">
        work_id, user_id, project_id,  dept_id, work_time, work_day, status, reviewer_id, des, reason, type, is_overtime, create_time, modify_time
    </sql>

    <select id="statisticsByProjectType" resultMap="monthlyWorkHourStatistics">
        select CASE WHEN type = 1 THEN "项目" WHEN type = 2 THEN "商机" END AS type, count(1),sum(work_time)
        from
        <include refid="table"/>
        where user_id = #{userId} AND type in (1,2) AND work_day >= #{currentMonthFirstDay}
        group by type
    </select>

    <select id="listByDateAndUserId" resultMap="dayWorkTimeAndType">
        select user_id,day(work_day),CASE when `type` = 3 then "请假" when `type` = 4 then "调休" else "正常" end AS `type`,
        sum(work_time)
        from
        <include refid="table"/>
        where year(work_day) = #{year} AND month(work_day) = #{month} AND (status = 2 OR status=5)AND user_id IN
        <foreach collection="userIds" separator="," close=")" item="userId" open="(">
            #{userId}
        </foreach>
        group by user_id,day(work_day), CASE when `type` = 3 then "请假" when `type` = 4 then "调休" else "正常" end
        order by day(work_day)
    </select>

    <select id="getCountByCondition" resultType="integer" parameterType="map">
        select count(1)
        from
        <include refid="table"/>
        <where>
            <include refid="criteria"/>
            <if test="startDay != null">
                AND work_day>=#{startDay}
            </if>
            <if test="projectIds != null">
                AND project_id IN
                <foreach collection="projectIds" item="projectId" open="(" close=")" separator=",">
                    #{projectId}
                </foreach>
            </if>
            <if test="statusArray != null">
                AND `status` IN
                <foreach collection="statusArray" item="workStatus" open="(" close=")" separator=",">#{workStatus}
                </foreach>
            </if>
            <if test="typeArray != null">
                AND `type` IN
                <foreach collection="typeArray" item="type" open="(" close=")" separator=",">
                    #{type}
                </foreach>
            </if>
        </where>
    </select>

    <select id="getWorkTimeAndCostCollect" resultMap="workTimeAndCostCollect" >
        SELECT CASE t.type WHEN  1 THEN "项目" WHEN 2 THEN "商机" WHEN  3 THEN "请假" WHEN 4 THEN "调休"  WHEN 5 THEN "外部商务" WHEN 6 THEN "内部培训、技术准备、管理" WHEN 7 THEN "其他非项目/商机工作" END AS type,t.dept_id AS dept_id,
        t.project_id AS project_id ,MIN(t.work_day) AS first_time,MAX(t.work_day) AS last_time,ROUND(SUM(t.work_time)/8,2) AS
        total_time,ROUND((SUM(t.work_time))/8*10,2) AS cost,dept_name AS dept_name,project_name
        FROM work_time_order t LEFT JOIN work_project p ON t.project_id=p.id LEFT JOIN work_dept d ON t.dept_id=d.id
        WHERE status IN (2,5)
        <if test="projectIds != null">
        AND (t.project_id IN
            <foreach collection="projectIds" item="projectId" open="(" close=")" separator=",">
                #{projectId}
            </foreach>
        OR t.project_id IS null)
        </if>
        <if test="startTime != null">
            AND work_day >= #{startTime}
        </if>
         <if test="deptId != null">
            AND t.dept_id = #{deptId}
        </if>
        AND t.type in
        <foreach collection="types" item="type" open="(" close=")" separator=",">
            #{type}
        </foreach>
        group by t.type,t.dept_id, t.project_id,dept_name,p.project_name
        order by t.dept_id
    </select>

    <select id="getDaysByDateAndStatus" resultType="date">
        select distinct(work_day)
        from
        <include refid="table"/>
        where work_day >= #{firstDayOfMonth} AND user_id = #{userId}
    </select>
    <select id="geByMonth" resultType="cn.wisenergy.model.app.WorkTimeOrder">
        SELECT
        <include refid="Base_Column_List"/>
        FROM
        <include refid="table"/>
        <where>
            <if test="null != userId">
                AND user_id = #{userId}
            </if>
            <if test="null != workMonth">
                AND DATE_FORMAT(work_day, '%Y%m') = DATE_FORMAT(#{workMonth} ,'%Y%m')
            </if>
            <if test="null != status">
                AND status = #{status}
            </if>
        </where>


    </select>
    <select id="getAutoOrder" resultType="cn.wisenergy.model.app.WorkTimeOrder">
        select
        <include refid="Base_Column_List"/>
        FROM
        <include refid="table"/>
        <where>
            status IN (1,4)
            AND TIMESTAMPDIFF(HOUR,modify_time,now()) > #{autoExamine}
        </where>


    </select>


    <select id="getUserProjectWorkTimeStatistics" resultMap="userWorkTimeStatisticsByProject">
        SELECT u.id AS user_id ,u.`name` AS user_name, t.project_id AS project_id
                ,case t.type when 1 then '项目' when 2 then '商机' when 5 then '外部商务/技术交流' when 6 then '内部培训/技术准备/管理' when 7 then '其他非项目/商机工作' end AS project_type
                ,p.project_name AS project_name, case t.is_overtime when 1 then '加班' ELSE '正常' end AS is_overtime,SUM(t.work_time) AS work_time
        from work_time_order t join work_project p on t.project_id = p.id join  work_user u on t.user_id = u.id
        where
        t.work_day &lt; #{endDate}
        <if test="startDate != null">
            AND   t.work_day > #{startDate}
        </if>
          AND p.is_conclusion=#{status} AND t.type not in(3,4)
        <if test="projectIds != null">
            AND project_id in
            <foreach collection="projectIds" item="projectId" open="(" close=")" separator=",">
                #{projectId}
            </foreach>
        </if>
        GROUP BY u.id,u.`name`,t.project_id,t.type,p.project_name, t.is_overtime
    </select>
</mapper>