package com.uas.account.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import org.springframework.dao.DataAccessException;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.ResultSetExtractor;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.ui.ModelMap;

import com.alibaba.druid.util.StringUtils;
import com.uas.account.core.Page;
import com.uas.account.entity.InvitationRecord;
import com.uas.account.entity.PartnershipRecord;

@Repository
public class PartnershipRecordDaoImpl extends BaseDao implements PartnershipRecordDao {

    @Override
    public PartnershipRecord save(PartnershipRecord record) {
        if (record.getId() == null && !StringUtils.isEmpty(record.getCustUID())) {
            if (!StringUtils.isEmpty(record.getVendUID())) {
                Long id = jdbcTemplate.queryForObject(
                        "select min(id) from partnershiprecord where custuid=? and venduid=?", Long.class,
                        record.getCustUID(), record.getVendUID());
                record.setId(id);
            }
        }
        if (record.getId() == null) {
            record.setId(generateId("partnership_seq"));
            jdbcTemplate.update(
					"insert into partnershiprecord(id,appid,requestdate,custname,custuid,custusername,custusercode,custusertel,custuseremail,vendname,venduid,statuscode,status,method) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
                    record.getId(), record.getAppId(), record.getRequestDate(), record.getCustName(),
                    record.getCustUID(), record.getCustUserName(), record.getCustUserCode(), record.getCustUserTel(),
                    record.getCustUserEmail(), record.getVendName(), record.getVendUID(), record.getStatusCode(),
					record.getStatus(), record.getMethod());
        } else {
            jdbcTemplate.update(
					"update partnershiprecord set appid=?,requestdate=?,custusername=?,custusercode=?,custusertel=?,custuseremail=?,statuscode=?,status=?,vendusername=?,vendusertel=?,venduseremail=?,vendusercode=?,reason=?,method=? where id=?",
                    record.getAppId(), record.getRequestDate(), record.getCustUserName(), record.getCustUserCode(),
                    record.getCustUserTel(), record.getCustUserEmail(), record.getStatusCode(), record.getStatus(),
                    record.getVendUserName(), record.getVendUserTel(), record.getVendUserEmail(),
					record.getVendUserCode(), record.getReason(), record.getMethod(), record.getId());
        }
        return record;
    }

    @Override
    public Page<PartnershipRecord> findAllSendView(int pageNumber, String businessCode, String custUserName,
                                                   int pageSize, String name, String custuid, String custusercode, Integer status) {
        StringBuffer countSql = new StringBuffer("select count(1) from partnershiprecord where 1=1");
        StringBuffer querySql = new StringBuffer(
                "select * from (select t.*,rownum r from (select * from partnershiprecord where 1=1");
        Object[] args = new Object[]{};
        if (null != custuid) {
            countSql.append("and custuid=?");
            querySql.append("and custuid=?");
            args = Arrays.copyOf(args, args.length + 1);
            args[args.length - 1] = custuid;
        }
        if (null != custusercode) {
            countSql.append("and custusercode=?");
            querySql.append("and custusercode=?");
            args = Arrays.copyOf(args, args.length + 1);
            args[args.length - 1] = custusercode;
        }
        if (null != status) {
            countSql.append(" and statuscode=?");
            querySql.append(" and statuscode=?");
            args = Arrays.copyOf(args, args.length + 1);
            args[args.length - 1] = status;
        }
        if (!StringUtils.isEmpty(name)) {
            countSql.append(" and upper(vendname) like upper('%").append(name).append("%')");
            querySql.append(" and upper(vendname) like upper('%").append(name).append("%')");
        }
        if (!StringUtils.isEmpty(custUserName)) {
            countSql.append(" and custusername like '%").append(custUserName).append("%'");
            querySql.append(" and custusername like '%").append(custUserName).append("%'");
        }
        if (!StringUtils.isEmpty(businessCode)) {
            countSql.append(" and venduid = '").append(businessCode).append("'");
            querySql.append(" and venduid = '").append(businessCode).append("'");
        }
        int total = count(countSql.toString(), args);

        querySql.append(" order by id desc,vendname) t where rownum <= ?) where r >= ?");
        args = Arrays.copyOf(args, args.length + 2);
        args[args.length - 2] = pageNumber * pageSize;
        args[args.length - 1] = (pageNumber - 1) * pageSize + 1;
        List<PartnershipRecord> content = null;
        try {
            content = jdbcTemplate.query(querySql.toString(),
                    new BeanPropertyRowMapper<PartnershipRecord>(PartnershipRecord.class), args);
        } catch (EmptyResultDataAccessException e) {

        }
        return new Page<PartnershipRecord>(pageNumber, pageSize, content, total);
    }

    @Override
    public Page<PartnershipRecord> findAllReceivedView(int pageNumber, String businessCode, String custUserName,
                                                       int pageSize, String name, String venduid, Integer status) {
        StringBuffer countSql = new StringBuffer("select count(1) from partnershiprecord where 1=1");
        StringBuffer querySql = new StringBuffer(
                "select * from (select t.*,rownum r from (select * from partnershiprecord where 1=1");
        Object[] args = new Object[]{};
        if (null != venduid) {
            countSql.append("and venduid=?");
            querySql.append("and venduid=?");
            args = Arrays.copyOf(args, args.length + 1);
            args[args.length - 1] = venduid;
        }
        if (null != status) {
            countSql.append(" and statuscode=?");
            querySql.append(" and statuscode=?");
            args = Arrays.copyOf(args, args.length + 1);
            args[args.length - 1] = status;
        }
        if (!StringUtils.isEmpty(name)) {
            countSql.append(" and upper(custname) like upper('%").append(name).append("%')");
            querySql.append(" and upper(custname) like upper('%").append(name).append("%')");
        }
        if (!StringUtils.isEmpty(custUserName)) {
            countSql.append(" and custusername like '%").append(custUserName).append("%'");
            querySql.append(" and custusername like '%").append(custUserName).append("%'");
        }
        if (!StringUtils.isEmpty(businessCode)) {
            countSql.append(" and venduid = '").append(businessCode).append("'");
            querySql.append(" and venduid = '").append(businessCode).append("'");
        }
        int total = count(countSql.toString(), args);

        querySql.append(" order by id desc,vendname) t where rownum <= ?) where r >= ?");
        args = Arrays.copyOf(args, args.length + 2);
        args[args.length - 2] = pageNumber * pageSize;
        args[args.length - 1] = (pageNumber - 1) * pageSize + 1;
        List<PartnershipRecord> content = null;
        try {
            content = jdbcTemplate.query(querySql.toString(),
                    new BeanPropertyRowMapper<PartnershipRecord>(PartnershipRecord.class), args);
        } catch (EmptyResultDataAccessException e) {

        }
        return new Page<PartnershipRecord>(pageNumber, pageSize, content, total);
    }

    @Override
    public PartnershipRecord findById(Long id) {
        try {
            return jdbcTemplate.queryForObject("select * from partnershiprecord where id=?", getRowMapper(), id);
        } catch (EmptyResultDataAccessException e) {
            return null;
        }
    }

    private RowMapper<PartnershipRecord> getRowMapper() {
        return new RowMapper<PartnershipRecord>() {

            @Override
            public PartnershipRecord mapRow(ResultSet rs, int rowNum) throws SQLException {
                PartnershipRecord partner = new PartnershipRecord();
                partner.setId(rs.getLong("id"));
                partner.setAppId(rs.getString("appid"));
                partner.setCustName(rs.getString("custname"));
                partner.setCustUID(rs.getString("custuid"));
                partner.setCustUserName(rs.getString("custusername"));
                partner.setCustUserCode(rs.getString("custusercode"));
                partner.setCustUserEmail(rs.getString("custuseremail"));
                partner.setCustUserTel(rs.getString("custusertel"));
                partner.setRequestDate(rs.getDate("requestdate"));
                partner.setStatus(rs.getString("status"));
                partner.setStatusCode(rs.getInt("statuscode"));
                partner.setVendUID(rs.getString("venduid"));
                partner.setVendName(rs.getString("vendname"));
                partner.setVendUserCode(rs.getString("vendusercode"));
                partner.setVendUserName(rs.getString("vendusername"));
                partner.setOperateDate(rs.getDate("operatedate"));
                partner.setReason(rs.getString("reason"));
                partner.setVendUserTel(rs.getString("vendusertel"));
                partner.setVendUserEmail(rs.getString("venduseremail"));
                return partner;
            }

        };
    }

    @Override
    public PartnershipRecord findByCustUIDAndVendUID(String custuid, String venduid) {
        try {
            return jdbcTemplate
                    .queryForObject(
                            "select * from partnershiprecord where custuid = '" + custuid + "' and venduid = '" + venduid + "'",
                            new BeanPropertyRowMapper<PartnershipRecord>(PartnershipRecord.class));
        } catch (EmptyResultDataAccessException e) {
            return null;
        }
    }

    @Override
    public ModelMap getSendRequestCount(String custuid) {
        return jdbcTemplate.query("select status,count(1) c from partnershiprecord where custuid = '" + custuid
                        + "' group by status order by count(1) desc",
                new ResultSetExtractor<ModelMap>() {

                    @Override
                    public ModelMap extractData(ResultSet rs) throws SQLException, DataAccessException {
                        ModelMap map = new ModelMap();
                        while (rs.next()) {
                            map.put(rs.getString(1), rs.getInt(2));
                        }
                        return map;
                    }

                });
    }

    @Override
    public ModelMap getReceivedRequestCount(String venduid) {
        return jdbcTemplate.query("select status,count(1) c from partnershiprecord where venduid = '" + venduid
                + "' group by status order by count(1) desc", new ResultSetExtractor<ModelMap>() {

            @Override
            public ModelMap extractData(ResultSet rs) throws SQLException, DataAccessException {
                ModelMap map = new ModelMap();
                while (rs.next()) {
                    map.put(rs.getString(1), rs.getInt(2));
                }
                return map;
            }

        });
    }

    @Override
    public int getAllSendCount(String custuid) {
        return count("from partnershiprecord where custuid = ?", custuid);
    }

    @Override
    public int getAllReceivedCount(String venduid) {
        return count("from partnershiprecord where venduid = ?", venduid);
    }

    @Override
    public Page<PartnershipRecord> findBySpaceUidAndStatusCode(String businessCode, Integer statusCode, String keyword,
                                                               int pageNumber, int pageSize) {
        StringBuffer countSql = new StringBuffer("select count(1) from v$partnershiprecord where 1=1");
        StringBuffer querySql = new StringBuffer(
                "select * from (select t.*,rownum r from (select * from v$partnershiprecord where 1=1");
        Object[] args = new Object[]{};
        if (!StringUtils.isEmpty(businessCode) && !StringUtils.isEmpty(keyword)) {
            // ((custuid = '56749203' and (vendname like '%胜芳%' or venduid like '%123%')) or (venduid = '56749203' and (custname like '%胜芳%' or custuid like '%123%')))
            querySql.append(" and ((venduid = '").append(businessCode).append("' and (custname like '%").append(keyword)
                    .append("%' or custuid like '%").append(keyword).append("%' or custadminname like '%").append(keyword)
                    .append("%' or custadmintel like '%").append(keyword).append("%' or custadminemail like '%").append(keyword)
                    .append("%' or custprofession like '%").append(keyword).append("%' or custtags like '%").append(keyword)
                    .append("%' or custuu like '%").append(keyword).append("%' or custaddress like '%").append(keyword)
                    .append(" %')) or ((custuid = '").append(businessCode).append("' and (vendname like '%").append(keyword)
                    .append("%' or venduid like '%").append(keyword).append("%' or vendadminname like '%").append(keyword)
                    .append("%' or vendadmintel like '%").append(keyword).append("%' or vendadminemail like '%").append(keyword)
                    .append("%' or vendprofession like '%").append(keyword).append("%' or vendtags like '%").append(keyword)
                    .append("%' or venduu like '%").append(keyword).append("%' or vendaddress like '%").append(keyword).append("%'))))");

            countSql.append(" and ((venduid = '").append(businessCode).append("' and (custname like '%").append(keyword)
                    .append("%' or custuid like '%").append(keyword).append("%' or custadminname like '%").append(keyword)
                    .append("%' or custadmintel like '%").append(keyword).append("%' or custadminemail like '%").append(keyword)
                    .append("%' or custprofession like '%").append(keyword).append("%' or custtags like '%").append(keyword)
                    .append("%' or custuu like '%").append(keyword).append("%' or custaddress like '%").append(keyword)
                    .append(" %')) or ((custuid = '").append(businessCode).append("' and (vendname like '%").append(keyword)
                    .append("%' or venduid like '%").append(keyword).append("%' or vendadminname like '%").append(keyword)
                    .append("%' or vendadmintel like '%").append(keyword).append("%' or vendadminemail like '%").append(keyword)
                    .append("%' or vendprofession like '%").append(keyword).append("%' or vendtags like '%").append(keyword)
                    .append("%' or venduu like '%").append(keyword).append("%' or vendaddress like '%").append(keyword).append("%'))))");
        }
        if (!StringUtils.isEmpty(businessCode) && StringUtils.isEmpty(keyword)) {
            querySql.append(" and (venduid = '").append(businessCode).append("' or custuid='").append(businessCode)
                    .append("')");
            countSql.append(" and (venduid = '").append(businessCode).append("' or custuid='").append(businessCode)
                    .append("')");
        }
        if (statusCode != null) {
            countSql.append(" and statusCode=").append(statusCode);
            querySql.append(" and statusCode=").append(statusCode);
        }
        int total = count(countSql.toString(), args);
        // 311申请中， 310 已拒绝， 313 已激活 需要按申请中、已激活、已拒绝排序，所以用replace将311替换成333再排序。
        querySql.append(" order by translate(statuscode, 311, 333) desc,id desc,vendname) t where rownum <= ?) where r >= ?");
        args = Arrays.copyOf(args, args.length + 2);
        args[args.length - 2] = pageNumber * pageSize;
        args[args.length - 1] = (pageNumber - 1) * pageSize + 1;
        List<PartnershipRecord> content = null;
        try {
            content = jdbcTemplate.query(querySql.toString(),
                    new BeanPropertyRowMapper<PartnershipRecord>(PartnershipRecord.class), args);
        } catch (EmptyResultDataAccessException e) {

        }
        return new Page<PartnershipRecord>(pageNumber, pageSize, content, total);
    }

    @Override
    public Page<PartnershipRecord> findBySpaceUidAndStatusCodeFilterByPartnerUUs(String businessCode, Integer statusCode, String keyword,
                                                                                 List<Long> partnerUUs, int pageNumber, int pageSize) {
        StringBuffer countSql = new StringBuffer("select * from partnershiprecord where 1=1");
        StringBuffer querySql = new StringBuffer(
                "select * from (select t.*,rownum r from (select * from partnershiprecord where 1=1");
        Object[] args = new Object[]{};
        if (!StringUtils.isEmpty(businessCode) && !StringUtils.isEmpty(keyword)) {
            // ((custuid = '56749203' and (vendname like '%胜芳%' or venduid like '%123%')) or (venduid = '56749203' and (custname like '%胜芳%' or custuid like '%123%')))
            querySql.append(" and ((venduid = '").append(businessCode).append("' and (custname like '%").append(keyword)
                    .append("%' or custuid like '%").append(keyword).append("%' or custusername like '%").append(keyword)
                    .append("%' or vendusername like '%").append(keyword).append("%')) or (custuid='").append(businessCode)
                    .append("' and (vendname like '%").append(keyword).append("%' or venduid like '%").append(keyword)
                    .append("%' or custusername like '%").append(keyword).append("%' or vendusername like '%").append(keyword)
                    .append("%')))");
            countSql.append(" and ((venduid = '").append(businessCode).append("' and (custname like '%").append(keyword)
                    .append("%' or custuid like '%").append(keyword).append("%' or custusername like '%").append(keyword)
                    .append("%' or vendusername like '%").append(keyword).append("%')) or (custuid='").append(businessCode)
                    .append("' and (vendname like '%").append(keyword).append("%' or venduid like '%").append(keyword)
                    .append("%' or custusername like '%").append(keyword).append("%' or vendusername like '%").append(keyword)
                    .append("%')))");
        }
        if (!StringUtils.isEmpty(businessCode) && StringUtils.isEmpty(keyword)) {
            querySql.append(" and (venduid = '").append(businessCode).append("' or custuid='").append(businessCode)
                    .append("')");
            countSql.append(" and (venduid = '").append(businessCode).append("' or custuid='").append(businessCode)
                    .append("')");
        }
        if (statusCode != null) {
            countSql.append(" and statuscode=").append(statusCode);
            querySql.append(" and statuscode=").append(statusCode);
        }
        MapSqlParameterSource parameters = new MapSqlParameterSource("dialectuids", partnerUUs);
        // 不要直接拼SQL，防参数过多出错
        NamedParameterJdbcTemplate namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(jdbcTemplate);
        countSql.append(" and custuid not in (select uid_ from ac$userspaces where dialectuid in (:dialectuids))").append(" and venduid not in (select uid_ from ac$userspaces where dialectuid in (:dialectuids))");
        querySql.append(" and custuid not in (select uid_ from ac$userspaces where dialectuid in (:dialectuids))").append(" and venduid not in (select uid_ from ac$userspaces where dialectuid in (:dialectuids))");
        int total = namedParameterJdbcTemplate.query(countSql.toString(), parameters, getRowMapper()).size();
        args = Arrays.copyOf(args, args.length + 2);
        args[args.length - 2] = pageNumber * pageSize;
        args[args.length - 1] = (pageNumber - 1) * pageSize + 1;
        parameters.addValue("rowceil", pageNumber * pageSize);
        parameters.addValue("rowfloor", (pageNumber - 1) * pageSize + 1);
        // 311申请中， 310 已拒绝， 313 已激活 需要按申请中、已激活、已拒绝排序，所以用replace将311替换成333再排序。
        querySql.append(" order by translate(statuscode, 311, 333) desc,id desc,vendname) t where rownum <= :rowceil) where r >= :rowfloor");
        List<PartnershipRecord> content = null;
        try {
            content = namedParameterJdbcTemplate.query(querySql.toString(), parameters, getRowMapper());
        } catch (EmptyResultDataAccessException e) {

        }
        return new Page<PartnershipRecord>(pageNumber, pageSize, content, total);
    }

    @Override
    public int getRequestTodo(String businessCode) {
        return count("from partnershiprecord where statuscode = 311 and venduid = ?", businessCode);
    }

    @Override
    public void saveInvitation(InvitationRecord record) {
        if (record.getEnuu() != null && record.getVendname() != null) {
            Long id = jdbcTemplate.queryForObject(
                    "select min(in_id) from invitationrecords where in_enuu=? and in_vendname=?", Long.class,
                    record.getEnuu(), record.getVendname());
            record.setId(id);
        }
        if (record.getId() == null) {
            record.setId(generateId("invitationrecords_seq"));
            jdbcTemplate.update(
                    "insert into invitationrecords(in_id,in_enuu,in_businesscode,in_useruu,in_date,in_vendname,in_vendusername,in_vendusertel,in_venduseremail,in_count) values (?,?,?,?,?,?,?,?,?,?)",
                    record.getId(), record.getEnuu(), record.getBussinesscode(), record.getUseruu(), new Date(),
                    record.getVendname(), record.getVendusername(), record.getVendusertel(), record.getVenduseremail(),
                    record.getCount());
        } else {
            jdbcTemplate.update(
                    "update invitationrecords set in_enuu=?,in_businesscode=?,in_useruu=?,in_date=?,in_vendname=?,in_vendusername=?,in_vendusertel=?,in_venduseremail=?,in_count=? where in_id=?",
                    record.getEnuu(), record.getBussinesscode(), record.getUseruu(), new Date(), record.getVendname(),
                    record.getVendusername(), record.getVendusertel(), record.getVenduseremail(), record.getCount(),
                    record.getId());
        }
    }

    @Override
    public List<InvitationRecord> findByVendname(String vendname) {
        if (!StringUtils.isEmpty(vendname)) {
            try {
                return jdbcTemplate
                        .query("select distinct(in_businesscode) bussinesscode,in_useruu useruu from invitationrecords where upper(in_vendname) = upper('"
                                + vendname + "')", new BeanPropertyRowMapper<InvitationRecord>(InvitationRecord.class));
            } catch (EmptyResultDataAccessException e) {
                return null;
            }
        }
        return null;
    }

}
