<?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.yifu.cloud.plus.v1.yifu.salary.mapper.TAverageSalaryMapper">

	<resultMap id="tAverageSalaryMap" type="com.yifu.cloud.plus.v1.yifu.salary.entity.TAverageSalary">
		<id property="id" column="ID"/>
		<result property="empIdcard" column="EMP_IDCARD"/>
		<result property="averageSalary" column="AVERAGE_SALARY"/>
		<result property="createMonth" column="CREATE_MONTH"/>
	</resultMap>

	<resultMap id="tAverageSalaryVoMap" type="com.yifu.cloud.plus.v1.yifu.salary.vo.TAverageSalaryVo">
		<result property="empIdcard" column="EMP_IDCARD"/>
		<result property="averageSalary" column="AVERAGE_SALARY"/>
	</resultMap>

	<!-- 删除不需要的数据 -->
	<delete id="deleteByCreateMonth">
		delete
		from t_average_salary
		where CREATE_MONTH in (
							   DATE_FORMAT(now(), '%Y%m'), DATE_FORMAT(DATE_SUB(NOW(), INTERVAL 2 MONTH), '%Y%m')
			)
	</delete>

	<!-- 生成需要的数据 -->
	<insert id="insertAverageSalary">
		insert into t_average_salary
		select CONCAT(DATE_FORMAT(now(), '%Y%m-'), a.ID)                                 ID
			 , a.EMP_IDCARD
			 , round(sum(a.RELAY_SALARY) / ifnull(count(DISTINCT a.SALARY_MONTH), 1), 2) AVERAGE_SALARY
			 , DATE_FORMAT(now(), '%Y%m')                                                CREATE_MONTH
		from t_salary_account a
		where a.DELETE_FLAG=0 and a.SALARY_MONTH >= date_format(DATE_SUB(NOW(), INTERVAL 1 YEAR), '%Y%m')
		GROUP BY a.EMP_IDCARD
	</insert>

	<select id="getAverageSalary" resultMap="tAverageSalaryVoMap">
		select x.* from
		(select a.EMP_IDCARD,a.AVERAGE_SALARY from view_average_cur_month a) x
		LEFT JOIN
		(select a.EMP_IDCARD,a.AVERAGE_SALARY from view_average_last_month a) y
		on x.EMP_IDCARD=y.EMP_IDCARD
		where (x.AVERAGE_SALARY <![CDATA[ <>  ]]> IFNULL(y.AVERAGE_SALARY,-1))
		<if test="idNum != null and idNum.size > 0">
			AND x.EMP_IDCARD in
			<foreach item="item" index="index" collection="idNum" open="(" separator="," close=")">
				#{item}
			</foreach>
		</if>
	</select>
</mapper>
