<?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="design">

  <!-- 설계의뢰 검색 조건 -->
  <sql id="designRequestSearchCondition">
    <if test="source_type != null and source_type != ''">
      AND r.source_type = #{source_type}
    </if>
    <if test="status != null and status != ''">
      AND r.status = #{status}
    </if>
    <if test="priority != null and priority != ''">
      AND r.priority = #{priority}
    </if>
    <if test="search != null and search != ''">
      AND (r.target_name ILIKE '%' || #{search} || '%'
        OR r.request_no ILIKE '%' || #{search} || '%'
        OR r.requester ILIKE '%' || #{search} || '%')
    </if>
  </sql>

  <select id="getDesignRequestList" parameterType="map" resultType="map">
    SELECT r.*,
      COALESCE(
        (SELECT JSON_AGG(
          JSON_BUILD_OBJECT(
            'id', h.id, 'step', h.step, 'history_date', h.history_date,
            'user_name', h.user_name, 'description', h.description
          )
        ) FILTER (WHERE h.id IS NOT NULL)
        FROM dsn_request_history h WHERE h.request_id = r.id
        ), '[]'::JSON
      ) AS history,
      COALESCE(
        (SELECT JSON_AGG(i.impact_type) FROM dsn_request_impact i WHERE i.request_id = r.id),
        '[]'::JSON
      ) AS impact

    FROM dsn_design_request r

    WHERE 1=1
    <include refid="common.companyCodeFilter"/>
    <include refid="designRequestSearchCondition"/>

    ORDER BY r.created_date DESC
    <include refid="common.pagination"/>
  </select>

  <select id="getDesignRequestListCnt" parameterType="map" resultType="int">
    SELECT COUNT(*)

    FROM dsn_design_request r

    WHERE 1=1
    <include refid="common.companyCodeFilter"/>
    <include refid="designRequestSearchCondition"/>
  </select>

  <!-- 프로젝트 검색 조건 -->
  <sql id="projectSearchCondition">
    <if test="status != null and status != ''">
      AND p.status = #{status}
    </if>
    <if test="search != null and search != ''">
      AND (p.name ILIKE '%' || #{search} || '%'
        OR p.project_no ILIKE '%' || #{search} || '%'
        OR p.customer ILIKE '%' || #{search} || '%')
    </if>
  </sql>

  <select id="getProjectList" parameterType="map" resultType="map">
    SELECT p.*,
      COALESCE(
        (SELECT JSON_AGG(
          JSON_BUILD_OBJECT(
            'id', t.id, 'name', t.name, 'category', t.category, 'assignee', t.assignee,
            'start_date', t.start_date, 'end_date', t.end_date, 'status', t.status,
            'progress', t.progress, 'priority', t.priority, 'remark', t.remark, 'sort_order', t.sort_order
          ) ORDER BY t.sort_order, t.start_date
        )
        FROM dsn_project_task t WHERE t.project_id = p.id
        ), '[]'::JSON
      ) AS tasks

    FROM dsn_project p

    WHERE 1=1
    <include refid="common.companyCodeFilter"/>
    <include refid="projectSearchCondition"/>

    ORDER BY p.created_date DESC
    <include refid="common.pagination"/>
  </select>

  <select id="getProjectListCnt" parameterType="map" resultType="int">
    SELECT COUNT(*)

    FROM dsn_project p

    WHERE 1=1
    <include refid="common.companyCodeFilter"/>
    <include refid="projectSearchCondition"/>
  </select>

  <!-- ECN 검색 조건 -->
  <sql id="ecnSearchCondition">
    <if test="status != null and status != ''">
      AND e.status = #{status}
    </if>
    <if test="search != null and search != ''">
      AND (e.ecn_no ILIKE '%' || #{search} || '%'
        OR e.target ILIKE '%' || #{search} || '%')
    </if>
  </sql>

  <select id="getEcnList" parameterType="map" resultType="map">
    SELECT e.*,
      COALESCE(
        (SELECT JSON_AGG(
          JSON_BUILD_OBJECT(
            'id', h.id, 'status', h.status, 'history_date', h.history_date,
            'user_name', h.user_name, 'description', h.description
          ) ORDER BY h.created_date
        ) FROM dsn_ecn_history h WHERE h.ecn_id = e.id
        ), '[]'::JSON
      ) AS history,
      COALESCE(
        (SELECT JSON_AGG(nd.dept_name) FROM dsn_ecn_notify_dept nd WHERE nd.ecn_id = e.id),
        '[]'::JSON
      ) AS notify_depts

    FROM dsn_ecn e

    WHERE 1=1
    <include refid="common.companyCodeFilter"/>
    <include refid="ecnSearchCondition"/>

    ORDER BY e.created_date DESC
    <include refid="common.pagination"/>
  </select>

  <select id="getEcnListCnt" parameterType="map" resultType="int">
    SELECT COUNT(*)

    FROM dsn_ecn e

    WHERE 1=1
    <include refid="common.companyCodeFilter"/>
    <include refid="ecnSearchCondition"/>
  </select>

  <!-- 설계의뢰 단건 -->
  <select id="getDesignRequestInfo" parameterType="map" resultType="map">
    SELECT r.*

    FROM dsn_design_request r

    WHERE r.id = #{id}
    <include refid="common.companyCodeFilter"/>

    LIMIT 1
  </select>

  <insert id="insertDesignRequest" parameterType="map" useGeneratedKeys="true" keyProperty="id">
    INSERT INTO dsn_design_request (
      request_no, source_type, request_date, due_date, priority, status,
      target_name, customer, req_dept, requester, designer, order_no,
      design_type, spec, change_type, drawing_no, urgency, reason,
      content, apply_timing, review_memo, project_id, ecn_no,
      writer, company_code
    ) VALUES (
      #{request_no}, #{source_type}, #{request_date}, #{due_date},
      COALESCE(#{priority}, 'NORMAL'), COALESCE(#{status}, 'PENDING'),
      #{target_name}, #{customer}, #{req_dept}, #{requester}, #{designer}, #{order_no},
      #{design_type}, #{spec}, #{change_type}, #{drawing_no}, #{urgency}, #{reason},
      #{content}, #{apply_timing}, #{review_memo}, #{project_id, jdbcType=INTEGER}, #{ecn_no},
      #{writer}, #{company_code}
    )
  </insert>

  <update id="updateDesignRequest" parameterType="map">
    UPDATE dsn_design_request SET
      source_type = #{source_type},
      request_date = #{request_date},
      due_date = #{due_date},
      priority = COALESCE(#{priority}, priority),
      status = COALESCE(#{status}, status),
      target_name = COALESCE(#{target_name}, target_name),
      customer = #{customer},
      req_dept = #{req_dept},
      requester = #{requester},
      designer = #{designer},
      order_no = #{order_no},
      design_type = #{design_type},
      spec = #{spec},
      change_type = #{change_type},
      drawing_no = #{drawing_no},
      urgency = #{urgency},
      reason = #{reason},
      content = #{content},
      apply_timing = #{apply_timing},
      review_memo = #{review_memo},
      project_id = #{project_id, jdbcType=INTEGER},
      ecn_no = #{ecn_no},
      updated_date = NOW()

    WHERE id = #{id}
    <include refid="common.companyCodeFilter"/>
  </update>

  <delete id="deleteDesignRequest" parameterType="map">
    DELETE FROM dsn_design_request

    WHERE id = #{id}
    <include refid="common.companyCodeFilter"/>
  </delete>

  <!-- 프로젝트 단건 -->
  <select id="getProjectInfo" parameterType="map" resultType="map">
    SELECT p.*

    FROM dsn_project p

    WHERE p.id = #{id}
    <include refid="common.companyCodeFilter"/>

    LIMIT 1
  </select>

  <insert id="insertProject" parameterType="map" useGeneratedKeys="true" keyProperty="id">
    INSERT INTO dsn_project (
      project_no, name, customer, description, status, manager,
      start_date, end_date, company_code, writer
    ) VALUES (
      #{project_no}, #{name}, #{customer}, #{description},
      COALESCE(#{status}, 'ACTIVE'), #{manager},
      #{start_date}, #{end_date}, #{company_code}, #{writer}
    )
  </insert>

  <update id="updateProject" parameterType="map">
    UPDATE dsn_project SET
      name = COALESCE(#{name}, name),
      customer = #{customer},
      description = #{description},
      status = COALESCE(#{status}, status),
      manager = #{manager},
      start_date = #{start_date},
      end_date = #{end_date},
      updated_date = NOW()

    WHERE id = #{id}
    <include refid="common.companyCodeFilter"/>
  </update>

  <delete id="deleteProject" parameterType="map">
    DELETE FROM dsn_project

    WHERE id = #{id}
    <include refid="common.companyCodeFilter"/>
  </delete>

  <!-- ECN 단건 -->
  <select id="getEcnInfo" parameterType="map" resultType="map">
    SELECT e.*

    FROM dsn_ecn e

    WHERE e.id = #{id}
    <include refid="common.companyCodeFilter"/>

    LIMIT 1
  </select>

  <insert id="insertEcn" parameterType="map" useGeneratedKeys="true" keyProperty="id">
    INSERT INTO dsn_ecn (
      ecn_no, target, description, change_reason, status,
      issued_by, apply_date, company_code, writer
    ) VALUES (
      #{ecn_no}, #{target}, #{description}, #{change_reason},
      COALESCE(#{status}, 'DRAFT'), #{issued_by}, #{apply_date},
      #{company_code}, #{writer}
    )
  </insert>

  <update id="updateEcn" parameterType="map">
    UPDATE dsn_ecn SET
      target = COALESCE(#{target}, target),
      description = #{description},
      change_reason = #{change_reason},
      status = COALESCE(#{status}, status),
      issued_by = #{issued_by},
      apply_date = #{apply_date},
      updated_date = NOW()

    WHERE id = #{id}
    <include refid="common.companyCodeFilter"/>
  </update>

  <delete id="deleteEcn" parameterType="map">
    DELETE FROM dsn_ecn

    WHERE id = #{id}
    <include refid="common.companyCodeFilter"/>
  </delete>

</mapper>
