<?php
namespace App\Models\article;

use CodeIgniter\Model;

class GroundCntModel extends Model
{
  // 지역 목록 조회
  public function getAreaList($sido = '', $gugun = '')
  {

    if (!empty($gugun)) {
      $gugun = substr($gugun, '0', '5');

      $sql = "SELECT a.region_cd, TRIM(REPLACE(a.region_nm, b.region_nm, '')) region_nm" .
        " FROM region_codes a" .
        " LEFT JOIN region_codes b ON b.region_cd = CONCAT(SUBSTR(a.region_cd,1,5),'00000')" .
        " WHERE a.region_cd LIKE concat(?, '%')" .
        " AND a.region_cd NOT LIKE '%00000'" .
        " AND a.region_cd LIKE '%00'" .
        " AND a.use_yn = 'Y'" .
        " ORDER BY a.region_nm ASC";

      $query = $this->db->query($sql, [$gugun]);

    } else if (!empty($sido)) {
      $chk_sido = substr($sido, '0', '2');

      if ($chk_sido === '36') {
        $sido = substr($sido, '0', '4');
        $sql = "SELECT a.region_cd, TRIM(REPLACE(a.region_nm, b.region_nm, '')) region_nm " .
          "FROM region_codes a " .
          "LEFT JOIN region_codes b ON b.region_cd = CONCAT(SUBSTR(a.region_cd,1,4),'000000') " .
          "WHERE a.region_cd LIKE concat(?, '%') " .
          "AND a.region_cd NOT LIKE '%000000' " .
          "AND a.region_cd LIKE '%00' " .
          "AND a.use_yn = 'Y' " .
          "AND EXISTS (SELECT 'x' FROM region_codes c WHERE c.region_cd LIKE CONCAT(SUBSTR(a.region_cd,1,5),'%') AND c.region_cd > CONCAT(SUBSTR(a.region_cd,1,5),'00000')) " .
          "ORDER BY a.region_nm ASC";
      } else {
        $sido = substr($sido, '0', '2');
        $sql = "SELECT a.region_cd, TRIM(REPLACE(a.region_nm, b.region_nm, '')) region_nm" .
          " FROM region_codes a" .
          " LEFT JOIN region_codes b ON b.region_cd = CONCAT(SUBSTR(a.region_cd,1,2),'00000000')" .
          " WHERE a.region_cd LIKE concat(?, '%')" .
          " AND a.region_cd NOT LIKE '%00000000'" .
          " AND a.region_cd LIKE '%00000'" .
          " AND a.use_yn = 'Y'" .
          " AND EXISTS (SELECT 'x' FROM region_codes c WHERE c.region_cd LIKE CONCAT(SUBSTR(a.region_cd,1,5),'%') AND c.region_cd > CONCAT(SUBSTR(a.region_cd,1,5),'00000'))" .
          " ORDER BY a.region_nm ASC";
      }

      $query = $this->db->query($sql, [$sido]);
    } else {
      $sql = "SELECT a.region_cd, a.region_nm " .
        "FROM region_codes a " .
        "WHERE (a.region_cd LIKE '%00000000' " .
        "AND a.use_yn = 'Y') " .
        "OR region_cd = 3611000000;";

      $query = $this->db->query($sql);
    }


    return $query->getResultArray();
  }

  // 소속본부조회
  public function getBonbuList()
  {
    $sql = "SELECT dept_sq, pdept_sq, dept_nm, dept_desc, dept_head, use_yn, depth, insert_tm, insert_usr, update_tm, update_usr, lft, rgt" .
      "  FROM departments" .
      " WHERE depth = 1" .
      "   AND use_yn = 'Y'" .
      " ORDER BY lft";

    $query = $this->db->query($sql);


    return $query->getResultArray();
  }

  // 소속팀 조회
  public function getTeamList()
  {
    $sql = "SELECT dept_sq, pdept_sq, dept_nm" .
      "  FROM departments" .
      " WHERE depth = 2" .
      "   AND use_yn = 'Y'" .
      " ORDER BY dept_nm";

    $query = $this->db->query($sql);


    return $query->getResultArray();
  }

  // 유저 조회
  public function getUserList()
  {
    $sql = "SELECT 
                    a.usr_sq, a.usr_id, a.usr_nm, a.dept_sq
                FROM users a
                WHERE 
                        a.usr_level IN ('3','4','40','5','50','6','60','61','62','7','8','70')
                        AND a.use_yn = 'Y'
                        AND EXISTS (
                        SELECT 'x' FROM departments a1 INNER JOIN departments a2 ON a2.lft BETWEEN a1.lft AND a1.rgt AND a2.use_yn = 'Y' 
                        WHERE 1=1 AND a2.dept_sq = a.dept_sq AND a1.use_yn = 'Y'
                )
                ORDER BY a.usr_level DESC, a.usr_nm ASC ";

    $query = $this->db->query($sql);

    return $query->getResultArray();
  }

  /**
   * 부서검색(상세)
   */
  public function getDeptDetail($dept_sq)
  {
    $sql = "SELECT dept_sq, pdept_sq, dept_nm, dept_desc, dept_head, use_yn, depth, insert_tm, insert_usr, update_tm, update_usr, lft, rgt" .
      "  FROM departments" .
      " WHERE dept_sq = ?";

    $data = [$dept_sq];
    $query = $this->db->query($sql, $data);
    $row = $query->getRowArray();

    return $row;
  }

  /**
   * 하위 부서 검색
   */
  public function getChildDept($dept)
  {
    $sql = "SELECT dept_sq, pdept_sq, dept_nm, dept_desc, dept_head, use_yn, depth, insert_tm, insert_usr, update_tm, update_usr, lft, rgt" .
      "  FROM departments" .
      " WHERE lft >= ?" .
      "   AND rgt <= ?" .
      " ORDER BY lft ASC";

    $data = [$dept['lft'], $dept['rgt']];
    $query = $this->db->query($sql, $data);

    return $query->getResultArray();
  }


  public function getTotalCount($data)
  {
    $usr_sq = session('usr_sq');
    $usr_level = session('usr_level');
    $dept_sq = session('dept_sq');

    $builder = $this->db->table('receipt a');

    $builder->select("COUNT(*) AS cnt");

    $builder->join('result b', 'b.rcpt_sq = a.rcpt_sq', 'left outer');
    $builder->join('region_codes c', 'a.rcpt_dong = c.region_cd');
    $builder->join('departments d', 'b.dept_sq = d.dept_sq', 'left outer');
    $builder->join('users u', 'b.usr_sq = u.usr_sq', 'left outer');
    $builder->join('result_imgs e', "e.rsrv_sq = b.rsrv_sq AND e.img_type = 'I1' AND e.use_yn = 'Y'", 'left outer');
    $builder->join('result_imgs f', "f.rsrv_sq = b.rsrv_sq AND e.img_type = 'I5' AND e.use_yn = 'Y'", 'left outer');

    $login_dept_info = $this->getDeptDetail($dept_sq);	// 로그인 사용자 소속부서정보
    $child_dept = [];													// 하위조직 목록
    if (strcmp($usr_level, '40') == 0) {
      $child = $this->getChildDept($login_dept_info);
      if (!empty($child)) {
        foreach ($child as $child) {
          $child_dept[] = $child['dept_sq'];
        }
      }
    }

    if ((int) $usr_level >= 4 && $usr_level != '45') {
      if (!empty($child_dept)) {
        $builder->whereIn('b.dept_sq', $child_dept);
      } else {
        $builder->where('b.usr_sq', $usr_sq);
      }
    }

    $builder->where('a.rcpt_tm >= DATE_ADD(CURDATE(), INTERVAL -3 MONTH)', null, false);
    $builder->where('b.use_yn', 'Y');
    $builder->where('f.img_path IS NOT NULL', null, false);


    if (!empty($data['rcpt_atclno'])) {
      $builder->where('a.rcpt_atclno', $data['rcpt_atclno']);
    } else {
      if ($data['schDateGb'] == '1') {
        $builder->where('a.rcpt_tm >=', $data['sdate'] . ' 00:00:00');
        $builder->where('a.rcpt_tm <=', $data['edate'] . ' 23:59:59');
      } else if ($data['schDateGb'] == '2') {
        $builder->where('b.rsrv_date >=', $data['sdate'] . ' 00:00:00');
        $builder->where('b.rsrv_date <=', $data['edate'] . ' 23:59:59');
      }

      // 지역
      if (!empty($data['dong'])) {
        $builder->where('a.rcpt_dong', $data['dong']);
      } else {
        if (!empty($data['gugun'])) {
          $builder->like('a.rcpt_gugun', substr($data['gugun'], 0, 5), 'after');
        } else {
          if (!empty($data['sido'])) {
            $builder->like('a.rcpt_gugun', substr($data['sido'], 0, 2), 'after');
          }
        }
      }

      // 관할조직
      if (!empty($data['bonbu'])) {
        $builder->where('d.pdept_sq', $data['bonbu']);
      }

      if (!empty($data['team'])) {
        $builder->where('d.dept_sq', $data['team']);
      }

      if (!empty($data['user'])) {
        $builder->where('d.usr_sq', $data['user']);
      }

      // 거래구분
      if (!empty($data['rcpt_product_info1'])) {
        $builder->where('a.rcpt_product_info1', $data['rcpt_product_info1']);
      }

      // 현재상태
      if (!empty($data['rcpt_stat1'])) {
        $builder->like('a.rcpt_stat', $data['rcpt_stat1'], 'after');
      }

      if (!empty($data['rcpt_stat2'])) {
        $builder->like('a.rcpt_stat', $data['rcpt_stat2'], 'after');
      }

      if (!empty($data['rcpt_stat3'])) {
        $builder->where('a.rcpt_stat', $data['rcpt_stat3']);
      }

      // 중개사명
      if (!empty($data['agent_nm'])) {
        $builder->like('a.agent_nm', $data['agent_nm'], 'both');
      }

      // 동영상촬영여부
      if (!empty($data['exp_movie_yn'])) {
        $builder->where('a.exp_movie_yn', $data['exp_movie_yn']);
      }

      // 홍보확인서여부
      if ($data['conf_img_yn'] == 'Y') {
        $builder->where('e.rsrv_sq IS NOT NULL', null, false);
      } else if ($data['conf_img_yn'] == 'N') {
        $builder->where('e.rsrv_sq IS NULL', null, false);
      }

      // 분양권
      if ($data['parcel_out_yn'] == 'Y') {
        $builder->where('a.parcel_out_yn', 'Y');
      } else if ($data['parcel_out_yn'] == 'N') {
        $builder->where('a.parcel_out_yn', 'N');
      }

      // CP ID
      if (!empty($data['rcpt_cpid'])) {
        if (strcmp($data['rcpt_cpid'], 'naver') == 0) {
          $builder->where('a.rcpt_cpid =', '');
        } else if (strcmp($data['rcpt_cpid'], 'cleancente') == 0) {
          $builder->where("a.rcpt_cpid !=", "");
        } else {
          $builder->where('a.rcpt_cpid', $data['rcpt_cpid']);
        }
      }

      // 매물종류
      if (!empty($data['rcpt_product'])) {
        $builder->where('a.parcel_out_yn', $data['rcpt_product']);
      }

      // 면적확인
      if ($data['exp_spc_yn'] == 'Y') {
        $builder->where('a.parcel_out_yn', 'Y');
      } else if ($data['exp_spc_yn'] == 'N') {
        $builder->where('a.parcel_out_yn', 'N');
      }

      // 체크리스트
      if ($data['check_list_img_yn'] == 'Y') {
        $builder->where('a.check_list_img_yn', 'Y');
      } else if ($data['check_list_img_yn'] == 'N') {
        $builder->where('a.check_list_img_yn', 'N');
      }

      // 평면도유무
      if ($data['ground_plan_yn'] == 'Y') {
        $builder->where('exists (select \'x\' from result_imgs imgs where imgs.rsrv_sq = b.rsrv_sq and imgs.img_type = \'I5\' and imgs.use_yn=\'Y\')', NULL, FALSE);
      } else if ($data['ground_plan_yn'] == 'N') {
        $builder->where('not exists (select \'x\' from result_imgs imgs where imgs.rsrv_sq = b.rsrv_sq and imgs.img_type = \'I5\' and imgs.use_yn=\'Y\')', NULL, FALSE);
      }

      // 평면도요청
      if (!empty($data['ground_plan'])) {
        $builder->where('a.ground_plan', $data['ground_plan']);
      }

      if (!empty($data['srchTxt'])) {
        // 중개사
        if ($data['srchType'] == '1') {
          $builder->groupStart()
            ->like('a.agent_nm', $data['srchTxt'])
            ->orLike('a.sellr_nm', $data['srchTxt'])
            ->groupEnd();

          // 주소                        
        } else if ($data['srchType'] == '2') {
          $builder->groupStart()
            ->like('a.rcpt_dtl_addr', $data['srchTxt'])
            ->orLike('a.rcpt_hscp_nm', $data['srchTxt'])
            ->orLike('a.rcpt_jibun_addr', $data['srchTxt'])
            ->groupEnd();

          // 사업자번호        
        } else if ($data['srchType'] == '3') {
          $builder->like('a.image_360_yn', $data['srchTxt'], 'both');
        } else {
          $builder->groupStart()
            ->like('a.agent_nm', $data['srchTxt'])
            ->orLike('a.sellr_nm', $data['srchTxt'])
            ->groupEnd();

          $builder->groupStart()
            ->like('a.rcpt_dtl_addr', $data['srchTxt'])
            ->orLike('a.rcpt_hscp_nm', $data['srchTxt'])
            ->orLike('a.rcpt_jibun_addr', $data['srchTxt'])
            ->groupEnd();

          $builder->like('a.image_360_yn', $data['srchTxt'], 'both');
        }
      }

    }

    $row = $builder->get()->getRowArray();
    return (int) ($row['cnt'] ?? 0);

  }

  public function getResultList($start, $end, $data)
  {
    $usr_sq = session('usr_sq');
    $usr_level = session('usr_level');
    $dept_sq = session('dept_sq');

    $builder = $this->db->table('receipt a');

    $builder->select("a.rcpt_sq
			       ,a.excls_spc
			       ,a.comp_sq
			       ,a.rcpt_floor
			       ,a.rcpt_floor2
			       ,a.rcpt_rating
			       ,a.rcpt_key
			   	,a.rcpt_atclno
			       ,a.rcpt_type
			       ,a.rcpt_product
			       ,a.rcpt_product_nm
			       ,a.rcpt_product_area
			       ,a.rcpt_product_price
			   	,a.rcpt_deal_type
			       ,a.rcpt_product_info1
			       ,a.rcpt_product_info2
			       ,a.rcpt_product_info3
			       ,a.rcpt_product_info4
			       ,a.rcpt_product_info5
			       ,a.rcpt_office
			       ,(CASE WHEN a.rcpt_agent IS NULL THEN 'N' ELSE 'Y' END) as rcpt_agent
			       ,a.rcpt_sido
			       ,a.rcpt_gugun
			       ,a.rcpt_dong
			       ,a.rcpt_bunji
			       ,a.rcpt_ho
			       ,a.rcpt_tm
			       ,a.rcpt_stat
			       ,a.rcpt_x
			       ,a.rcpt_y
			       ,a.rcpt_exps_type
			       ,a.cust_nm
			       ,a.cust_tel1
			       ,a.cust_tel2
			   	,a.rcpt_hscp_nm
			       ,a.cust_zip
			       ,a.cust_addr1
			       ,a.cust_addr2
			       ,a.remark
			   	,a.rcpt_cpid
			       ,a.agent_id
			       ,a.agent_nm
			       ,a.agent_head
			       ,a.agent_head_tel
			       ,a.agent_contact
			       ,a.agent_contact_tel
			       ,a.agent_fax
			       ,DATE_FORMAT(COALESCE(b.rsrv_date, a.rsrv_date), '%Y-%m-%d') AS rsrv_date
			       ,COALESCE(b.rsrv_tm_ap, a.rsrv_tm_ap) as rsrv_tm_ap
			       ,a.insert_usr
			       ,a.insert_tm
			       ,a.update_usr
			       ,a.update_tm
			       ,a.svc_type1
			       ,a.svc_type2
			       ,a.reconf_yn
			       ,b.rsrv_sq
			   	,b.dept_sq
			       ,b.usr_sq
			       ,b.rsrv_tm_hour
			       ,b.result_cd1
			       ,b.result_cd2
			       ,b.result_cd3
			   	,get_code_name('RECEIPT_STATUS1', b.result_cd1) AS result_cd1_nm
			   	,get_code_name('RECEIPT_STATUS2', b.result_cd2) AS result_cd2_nm
			   	,get_code_name('RECEIPT_STATUS3', b.result_cd3) AS result_cd3_nm
			       ,b.result_msg
			   	,b.photo_save_dt
			   	,b.rsrv_delay_dt
			   	,b.rsrv_cplt_dt
			   	,b.check_dt
			   	,b.check_cplt_dt
		       	,get_code_name('RECEIPT_STATUS1', substring(a.rcpt_stat, 1, 2)) AS rcpt_stat_nm
		       	,c.region_nm as addr
		           ,a.rcpt_dtl_addr
		           ,a.rcpt_jibun_addr
		           ,a.rcpt_etc_addr
		       	,d.pdept_sq
		       	,d.dept_nm
		       	,u.usr_nm
			   	,a.rcpt_exps_type
			   	,a.exp_photo_yn
			   	,a.exp_movie_yn
			   	,a.ground_plan
			       ,f.img_path
			       ,f.img_filenm
			       ,f.img_hannm
			       ,f.img_sq
			   	,f.cloud_upload_yn
			       ,( SELECT usr_nm FROM users WHERE users.usr_sq = f.insert_usr ) AS upload_usr_nm 
		       	,CASE (SELECT COUNT(1) FROM result_imgs WHERE rsrv_sq=b.rsrv_sq AND img_type = 'I1' AND use_yn = 'Y') WHEN 0 THEN 'N' ELSE 'Y' END conf_img_yn
		       	,CASE (SELECT COUNT(1) FROM result_imgs WHERE rsrv_sq=b.rsrv_sq AND img_type = 'I5' AND use_yn = 'Y') WHEN 0 THEN 'N' ELSE 'Y' END ground_plan_yn");

    $builder->join('result b', 'b.rcpt_sq = a.rcpt_sq', 'left outer');
    $builder->join('region_codes c', 'a.rcpt_dong = c.region_cd');
    $builder->join('departments d', 'b.dept_sq = d.dept_sq', 'left outer');
    $builder->join('users u', 'b.usr_sq = u.usr_sq', 'left outer');
    $builder->join('result_imgs e', "e.rsrv_sq = b.rsrv_sq AND e.img_type = 'I1' AND e.use_yn = 'Y'", 'left outer');
    $builder->join('result_imgs f', "f.rsrv_sq = b.rsrv_sq AND e.img_type = 'I5' AND e.use_yn = 'Y'", 'left outer');

    $login_dept_info = $this->getDeptDetail($dept_sq);	// 로그인 사용자 소속부서정보
    $child_dept = [];													// 하위조직 목록
    if (strcmp($usr_level, '40') == 0) {
      $child = $this->getChildDept($login_dept_info);
      if (!empty($child)) {
        foreach ($child as $child) {
          $child_dept[] = $child['dept_sq'];
        }
      }
    }

    if ((int) $usr_level >= 4 && $usr_level != '45') {
      if (!empty($child_dept)) {
        $builder->whereIn('b.dept_sq', $child_dept);
      } else {
        $builder->where('b.usr_sq', $usr_sq);
      }
    }

    $builder->where('a.rcpt_tm >= DATE_ADD(CURDATE(), INTERVAL -3 MONTH)', null, false);
    $builder->where('b.use_yn', 'Y');
    $builder->where('f.img_path IS NOT NULL', null, false);

    if (!empty($data['rcpt_atclno'])) {
      $builder->where('a.rcpt_atclno', $data['rcpt_atclno']);
    } else {
      if ($data['schDateGb'] == '1') {
        $builder->where('a.rcpt_tm >=', $data['sdate'] . ' 00:00:00');
        $builder->where('a.rcpt_tm <=', $data['edate'] . ' 23:59:59');
      } else if ($data['schDateGb'] == '2') {
        $builder->where('b.rsrv_date >=', $data['sdate'] . ' 00:00:00');
        $builder->where('b.rsrv_date <=', $data['edate'] . ' 23:59:59');
      }

      // 지역
      if (!empty($data['dong'])) {
        $builder->where('a.rcpt_dong', $data['dong']);
      } else {
        if (!empty($data['gugun'])) {
          $builder->like('a.rcpt_gugun', substr($data['gugun'], 0, 5), 'after');
        } else {
          if (!empty($data['sido'])) {
            $builder->like('a.rcpt_gugun', substr($data['sido'], 0, 2), 'after');
          }
        }
      }

      // 관할조직
      if (!empty($data['bonbu'])) {
        $builder->where('d.pdept_sq', $data['bonbu']);
      }

      if (!empty($data['team'])) {
        $builder->where('d.dept_sq', $data['team']);
      }

      if (!empty($data['user'])) {
        $builder->where('d.usr_sq', $data['user']);
      }

      // 거래구분
      if (!empty($data['rcpt_product_info1'])) {
        $builder->where('a.rcpt_product_info1', $data['rcpt_product_info1']);
      }

      // 현재상태
      if (!empty($data['rcpt_stat1'])) {
        $builder->like('a.rcpt_stat', $data['rcpt_stat1'], 'after');
      }

      if (!empty($data['rcpt_stat2'])) {
        $builder->like('a.rcpt_stat', $data['rcpt_stat2'], 'after');
      }

      if (!empty($data['rcpt_stat3'])) {
        $builder->where('a.rcpt_stat', $data['rcpt_stat3']);
      }

      // 중개사명
      if (!empty($data['agent_nm'])) {
        $builder->like('a.agent_nm', $data['agent_nm'], 'both');
      }

      // 동영상촬영여부
      if (!empty($data['exp_movie_yn'])) {
        $builder->where('a.exp_movie_yn', $data['exp_movie_yn']);
      }

      // 홍보확인서여부
      if ($data['conf_img_yn'] == 'Y') {
        $builder->where('e.rsrv_sq IS NOT NULL', null, false);
      } else if ($data['conf_img_yn'] == 'N') {
        $builder->where('e.rsrv_sq IS NULL', null, false);
      }

      // 분양권
      if ($data['parcel_out_yn'] == 'Y') {
        $builder->where('a.parcel_out_yn', 'Y');
      } else if ($data['parcel_out_yn'] == 'N') {
        $builder->where('a.parcel_out_yn', 'N');
      }

      // CP ID
      if (!empty($data['rcpt_cpid'])) {
        if (strcmp($data['rcpt_cpid'], 'naver') == 0) {
          $builder->where('a.rcpt_cpid =', '');
        } else if (strcmp($data['rcpt_cpid'], 'cleancente') == 0) {
          $builder->where("a.rcpt_cpid !=", "");
        } else {
          $builder->where('a.rcpt_cpid', $data['rcpt_cpid']);
        }
      }

      // 매물종류
      if (!empty($data['rcpt_product'])) {
        $builder->where('a.parcel_out_yn', $data['rcpt_product']);
      }

      // 면적확인
      if ($data['exp_spc_yn'] == 'Y') {
        $builder->where('a.parcel_out_yn', 'Y');
      } else if ($data['exp_spc_yn'] == 'N') {
        $builder->where('a.parcel_out_yn', 'N');
      }

      // 체크리스트
      if ($data['check_list_img_yn'] == 'Y') {
        $builder->where('a.check_list_img_yn', 'Y');
      } else if ($data['check_list_img_yn'] == 'N') {
        $builder->where('a.check_list_img_yn', 'N');
      }

      // 평면도유무
      if ($data['ground_plan_yn'] == 'Y') {
        $builder->where('exists (select \'x\' from result_imgs imgs where imgs.rsrv_sq = b.rsrv_sq and imgs.img_type = \'I5\' and imgs.use_yn=\'Y\')', NULL, FALSE);
      } else if ($data['ground_plan_yn'] == 'N') {
        $builder->where('not exists (select \'x\' from result_imgs imgs where imgs.rsrv_sq = b.rsrv_sq and imgs.img_type = \'I5\' and imgs.use_yn=\'Y\')', NULL, FALSE);
      }

      // 평면도요청
      if (!empty($data['ground_plan'])) {
        $builder->where('a.ground_plan', $data['ground_plan']);
      }


      if (!empty($data['srchTxt'])) {
        // 중개사
        if ($data['srchType'] == '1') {
          $builder->groupStart()
            ->like('a.agent_nm', $data['srchTxt'])
            ->orLike('a.sellr_nm', $data['srchTxt'])
            ->groupEnd();

          // 주소                        
        } else if ($data['srchType'] == '2') {
          $builder->groupStart()
            ->like('a.rcpt_dtl_addr', $data['srchTxt'])
            ->orLike('a.rcpt_hscp_nm', $data['srchTxt'])
            ->orLike('a.rcpt_jibun_addr', $data['srchTxt'])
            ->groupEnd();

          // 사업자번호        
        } else if ($data['srchType'] == '3') {
          $builder->like('a.image_360_yn', $data['srchTxt'], 'both');
        } else {
          $builder->groupStart()
            ->like('a.agent_nm', $data['srchTxt'])
            ->orLike('a.sellr_nm', $data['srchTxt'])
            ->groupEnd();

          $builder->groupStart()
            ->like('a.rcpt_dtl_addr', $data['srchTxt'])
            ->orLike('a.rcpt_hscp_nm', $data['srchTxt'])
            ->orLike('a.rcpt_jibun_addr', $data['srchTxt'])
            ->groupEnd();

          $builder->like('a.image_360_yn', $data['srchTxt'], 'both');
        }
      }

    }

    $builder->orderBy('a.rcpt_atclno', 'DESC');

    $builder->limit($end, $start);

    // echo $builder->getCompiledSelect(false);

    // log_message('debug', '[getResultList] SQL = ' . $builder->getCompiledSelect());

    return $builder->get()->getResultArray();

  }

  // 엑셀 다운로드
  public function getExcelList($data)
  {
    $usr_sq = session('usr_sq');
    $usr_level = session('usr_level');
    $dept_sq = session('dept_sq');

    $builder = $this->db->table('receipt a');

    $builder->select("get_code_name('RECEIPT_STATUS1', b.result_cd1) AS '현재상태',
                              a.rcpt_atclno AS '매물ID',
                              CONCAT(a.rsrv_date, ' ', b.rsrv_tm_ap) AS '예약일자',
                              CASE WHEN a.rcpt_jibun_addr IS NOT NULL 
                                THEN CONCAT(c.region_nm, ' ', a.rcpt_jibun_addr, ' ', a.rcpt_etc_addr)
                                ELSE CONCAT(c.region_nm, ' ', a.rcpt_dtl_addr, ' ', a.rcpt_ho)
                              END AS '주소',
                              CONCAT(a.rcpt_floor, '/', a.rcpt_floor2) AS '층',
                              a.excls_spc AS '면적',
                              IFNULL(a.rcpt_product_nm, a.rcpt_product) AS '매물종류',
                              d.dept_nm AS '관할조직(팀)',
                              u.usr_nm '방문담당',
                              ( SELECT usr_nm FROM users WHERE users.usr_sq = f.insert_usr ) AS '등록자명',
                              CASE (SELECT COUNT(1) FROM result_imgs WHERE rsrv_sq=b.rsrv_sq AND img_type = 'I5' AND use_yn = 'Y') WHEN 0 THEN 'N' ELSE 'Y' END AS '평면도유무',
                              a.ground_plan AS '평면도요청'");

    $builder->join('result b', 'b.rcpt_sq = a.rcpt_sq', 'left outer');
    $builder->join('region_codes c', 'a.rcpt_dong = c.region_cd');
    $builder->join('departments d', 'b.dept_sq = d.dept_sq', 'left outer');
    $builder->join('users u', 'b.usr_sq = u.usr_sq', 'left outer');
    $builder->join('result_imgs e', "e.rsrv_sq = b.rsrv_sq AND e.img_type = 'I1' AND e.use_yn = 'Y'", 'left outer');
    $builder->join('result_imgs f', "f.rsrv_sq = b.rsrv_sq AND e.img_type = 'I5' AND e.use_yn = 'Y'", 'left outer');

    $login_dept_info = $this->getDeptDetail($dept_sq);	// 로그인 사용자 소속부서정보
    $child_dept = [];													// 하위조직 목록
    if (strcmp($usr_level, '40') == 0) {
      $child = $this->getChildDept($login_dept_info);
      if (!empty($child)) {
        foreach ($child as $child) {
          $child_dept[] = $child['dept_sq'];
        }
      }
    }

    if ((int) $usr_level >= 4 && $usr_level != '45') {
      if (!empty($child_dept)) {
        $builder->whereIn('b.dept_sq', $child_dept);
      } else {
        $builder->where('b.usr_sq', $usr_sq);
      }
    }

    $builder->where('a.rcpt_tm >= DATE_ADD(CURDATE(), INTERVAL -3 MONTH)', null, false);
    $builder->where('b.use_yn', 'Y');
    $builder->where('f.img_path IS NOT NULL', null, false);

    if (!empty($data['rcpt_atclno'])) {
      $builder->where('a.rcpt_atclno', $data['rcpt_atclno']);
    } else {
      if ($data['schDateGb'] == '1') {
        $builder->where('a.rcpt_tm >=', $data['sdate'] . ' 00:00:00');
        $builder->where('a.rcpt_tm <=', $data['edate'] . ' 23:59:59');
      } else if ($data['schDateGb'] == '2') {
        $builder->where('b.rsrv_date >=', $data['sdate'] . ' 00:00:00');
        $builder->where('b.rsrv_date <=', $data['edate'] . ' 23:59:59');
      }

      // 지역
      if (!empty($data['dong'])) {
        $builder->where('a.rcpt_dong', $data['dong']);
      } else {
        if (!empty($data['gugun'])) {
          $builder->like('a.rcpt_gugun', substr($data['gugun'], 0, 5), 'after');
        } else {
          if (!empty($data['sido'])) {
            $builder->like('a.rcpt_gugun', substr($data['sido'], 0, 2), 'after');
          }
        }
      }

      // 관할조직
      if (!empty($data['bonbu'])) {
        $builder->where('d.pdept_sq', $data['bonbu']);
      }

      if (!empty($data['team'])) {
        $builder->where('d.dept_sq', $data['team']);
      }

      if (!empty($data['user'])) {
        $builder->where('d.usr_sq', $data['user']);
      }

      // 거래구분
      if (!empty($data['rcpt_product_info1'])) {
        $builder->where('a.rcpt_product_info1', $data['rcpt_product_info1']);
      }

      // 현재상태
      if (!empty($data['rcpt_stat1'])) {
        $builder->like('a.rcpt_stat', $data['rcpt_stat1'], 'after');
      }

      if (!empty($data['rcpt_stat2'])) {
        $builder->like('a.rcpt_stat', $data['rcpt_stat2'], 'after');
      }

      if (!empty($data['rcpt_stat3'])) {
        $builder->where('a.rcpt_stat', $data['rcpt_stat3']);
      }

      // 중개사명
      if (!empty($data['agent_nm'])) {
        $builder->like('a.agent_nm', $data['agent_nm'], 'both');
      }

      // 동영상촬영여부
      if (!empty($data['exp_movie_yn'])) {
        $builder->where('a.exp_movie_yn', $data['exp_movie_yn']);
      }

      // 홍보확인서여부
      if ($data['conf_img_yn'] == 'Y') {
        $builder->where('e.rsrv_sq IS NOT NULL', null, false);
      } else if ($data['conf_img_yn'] == 'N') {
        $builder->where('e.rsrv_sq IS NULL', null, false);
      }

      // 분양권
      if ($data['parcel_out_yn'] == 'Y') {
        $builder->where('a.parcel_out_yn', 'Y');
      } else if ($data['parcel_out_yn'] == 'N') {
        $builder->where('a.parcel_out_yn', 'N');
      }

      // CP ID
      if (!empty($data['rcpt_cpid'])) {
        if (strcmp($data['rcpt_cpid'], 'naver') == 0) {
          $builder->where('a.rcpt_cpid =', '');
        } else if (strcmp($data['rcpt_cpid'], 'cleancente') == 0) {
          $builder->where("a.rcpt_cpid !=", "");
        } else {
          $builder->where('a.rcpt_cpid', $data['rcpt_cpid']);
        }
      }

      // 매물종류
      if (!empty($data['rcpt_product'])) {
        $builder->where('a.parcel_out_yn', $data['rcpt_product']);
      }

      // 면적확인
      if ($data['exp_spc_yn'] == 'Y') {
        $builder->where('a.parcel_out_yn', 'Y');
      } else if ($data['exp_spc_yn'] == 'N') {
        $builder->where('a.parcel_out_yn', 'N');
      }

      // 체크리스트
      if ($data['check_list_img_yn'] == 'Y') {
        $builder->where('a.check_list_img_yn', 'Y');
      } else if ($data['check_list_img_yn'] == 'N') {
        $builder->where('a.check_list_img_yn', 'N');
      }

      // 평면도유무
      if ($data['ground_plan_yn'] == 'Y') {
        $builder->where('exists (select \'x\' from result_imgs imgs where imgs.rsrv_sq = b.rsrv_sq and imgs.img_type = \'I5\' and imgs.use_yn=\'Y\')', NULL, FALSE);
      } else if ($data['ground_plan_yn'] == 'N') {
        $builder->where('not exists (select \'x\' from result_imgs imgs where imgs.rsrv_sq = b.rsrv_sq and imgs.img_type = \'I5\' and imgs.use_yn=\'Y\')', NULL, FALSE);
      }

      // 평면도요청
      if (!empty($data['ground_plan'])) {
        $builder->where('a.ground_plan', $data['ground_plan']);
      }


      if (!empty($data['srchTxt'])) {
        // 중개사
        if ($data['srchType'] == '1') {
          $builder->groupStart()
            ->like('a.agent_nm', $data['srchTxt'])
            ->orLike('a.sellr_nm', $data['srchTxt'])
            ->groupEnd();

          // 주소                        
        } else if ($data['srchType'] == '2') {
          $builder->groupStart()
            ->like('a.rcpt_dtl_addr', $data['srchTxt'])
            ->orLike('a.rcpt_hscp_nm', $data['srchTxt'])
            ->orLike('a.rcpt_jibun_addr', $data['srchTxt'])
            ->groupEnd();

          // 사업자번호        
        } else if ($data['srchType'] == '3') {
          $builder->like('a.image_360_yn', $data['srchTxt'], 'both');
        } else {
          $builder->groupStart()
            ->like('a.agent_nm', $data['srchTxt'])
            ->orLike('a.sellr_nm', $data['srchTxt'])
            ->groupEnd();

          $builder->groupStart()
            ->like('a.rcpt_dtl_addr', $data['srchTxt'])
            ->orLike('a.rcpt_hscp_nm', $data['srchTxt'])
            ->orLike('a.rcpt_jibun_addr', $data['srchTxt'])
            ->groupEnd();

          $builder->like('a.image_360_yn', $data['srchTxt'], 'both');
        }
      }

    }

    $builder->orderBy('a.rcpt_atclno', 'DESC');

    // log_message('debug', '[getResultList] SQL = ' . $builder->getCompiledSelect());

    return $builder->get()->getResultArray();
  }
}