package com.yd.api.agms.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yd.api.agms.service.AgmsPractitionerService;
import com.yd.api.agms.vo.practitioner.*;
import com.yd.api.result.CommonResult;
import com.yd.api.result.CommonResultResponseVO;
import com.yd.dal.entity.customer.AclCustomer;
import com.yd.dal.entity.customer.AclPractitionerFileSharing;
import com.yd.dal.service.agms.AgmsPractitionerDALService;
import com.yd.dal.service.customer.AclPractitionerDALService;
import com.yd.dal.service.customer.AclPractitionerFileSharingDALService;
import com.yd.util.CommonUtil;
import com.yd.util.config.ZHBErrorConfig;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;

/**
 * @author xxy
 */
@Service("agmsPractitionerService")
public class AgmsPractitionerServiceImpl implements AgmsPractitionerService {

    @Autowired
    private AclPractitionerFileSharingDALService aclPractitionerFileSharingDalService;
    @Autowired
    private AgmsPractitionerDALService agmsPractitionerDALService;
    @Autowired
    private AclPractitionerDALService aclPractitionerDALService;

    @Override
    public PractitionerFileSharingSaveResponseVO practitionerFileSharingSave(PractitionerFileSharingSaveRequestVO requestVO) {
        PractitionerFileSharingSaveResponseVO responseVO = new PractitionerFileSharingSaveResponseVO();
        AclPractitionerFileSharing fileSharing = new AclPractitionerFileSharing();
        BeanUtils.copyProperties(requestVO, fileSharing);
        fileSharing.setUpdatedBy(requestVO.getLoginId());
        Long id = aclPractitionerFileSharingDalService.saveOrUpdate(fileSharing);
        responseVO.setId(id);
        responseVO.setCommonResult(new CommonResult(true, ZHBErrorConfig.getErrorInfo("800000")));
        return responseVO;
    }

    @Override
    public PractitionerFileSharingListResponseVO practitionerFileSharingList(PractitionerFileSharingListRequestVO requestVO) {
        PractitionerFileSharingListResponseVO responseVO = new PractitionerFileSharingListResponseVO();
        Long[] mdDropOptionIds = null;
        if (!CommonUtil.isNullOrBlank(requestVO.getMdDropOptionId())) {
            mdDropOptionIds = (Long[]) ConvertUtils.convert(requestVO.getMdDropOptionId().split(","), Long.class);
        }
        //等保调整
        if (null != requestVO.getPractitionerId()) {
            List<AclCustomer> findByObjSortable = aclPractitionerDALService.getAclCustomers(requestVO.getPractitionerId(), null);
            if (null == findByObjSortable) {
                responseVO.setCommonResult(new CommonResult(false, ZHBErrorConfig.getErrorInfo("630028")));
                return responseVO;
            }
        }

        PageInfo<PractitionerFileSharing> practitionerFileShares = agmsPractitionerDALService.practitionerFileSharingList(requestVO.getId(),
                requestVO.getPractitionerId(),
                requestVO.getShareCode(),
                mdDropOptionIds,
                requestVO.getIsActive(),
                requestVO.getPractitionerFileShares().getPageNum(),
                requestVO.getPractitionerFileShares().getPageSize());
        SharePractitionerInfo sharePractitionerInfo = agmsPractitionerDALService.findSharePractitioner(requestVO.getShareCode());
        responseVO.setSharePractitionerInfo(sharePractitionerInfo);
        responseVO.setPractitionerFileShares(practitionerFileShares);
        responseVO.setCommonResult(new CommonResult(true, ZHBErrorConfig.getErrorInfo("800000")));
        return responseVO;
    }

    @Override
    public PractitionerScheduleResponseVO practitionerSchedule(PractitionerScheduleRequestVO requestVO) {
        PractitionerScheduleResponseVO resp = new PractitionerScheduleResponseVO();

        Long practitionerId = requestVO.getPractitionerId();
        String trackDate = requestVO.getTrackTime();
//        if (StringUtils.isEmpty(trackDate) || null == practitionerId) {
//            resp.setCommonResult(new CommonResult(true, "经纪人id和查询时间不能为空"));
//            return resp;
//        }
        List<PractitionerScheduleInfo> list;
        try {
            PageInfo<PractitionerScheduleInfo> page = requestVO.getPage();
            PageHelper.startPage(page.getPageNum(), page.getPageSize(), null);

            list = agmsPractitionerDALService.practitionerSchedule(requestVO);

            PageInfo<PractitionerScheduleInfo> pageInfo = new PageInfo<>(list);

            // 设置resp
            resp.setList(pageInfo.getList());
            pageInfo.setList(null);
            resp.setPage(pageInfo);

            resp.setCommonResult(new CommonResult(true, ZHBErrorConfig.getErrorInfo("800000")));
        } catch (Exception e) {
            e.printStackTrace();
            resp.setCommonResult(new CommonResult(false, e.getMessage()));
        }
        return resp;
    }

    @Override
    public CommonResultResponseVO practitionerScheduleExport(PractitionerScheduleRequestVO requestVO, HttpServletResponse response) {
        CommonResultResponseVO resp = new CommonResultResponseVO();
        List<Map<String, Object>> dataList = agmsPractitionerDALService.practitionerScheduleExport(requestVO);
        // 表头和表名
        String[] columnName = new String[]{"序号", "经纪人姓名", "日期", "日程类型", "日程内容", "任务开始时间", "任务结束时间", "备注", "设置时间"};
        String tableName = "PractitionerSchedule" + System.currentTimeMillis() + ".csv";
        // 导出
        this.exportCSV(tableName, columnName, dataList, response);

        resp.setCommonResult(new CommonResult(true, ZHBErrorConfig.getErrorInfo("800000")));
        return resp;
    }

    @Override
    public PractitionerLeadsGoalsResponseVO practitionerLeadsGoals(PractitionerLeadsGoalsRequestVO requestVO) {
        PractitionerLeadsGoalsResponseVO resp = new PractitionerLeadsGoalsResponseVO();

        List<PractitionerLeadsGoalsInfo> list;
        try {
            PageInfo<PractitionerLeadsGoalsInfo> page = requestVO.getPage();
            PageHelper.startPage(page.getPageNum(), page.getPageSize(), null);

            list = agmsPractitionerDALService.practitionerLeadsGoals(requestVO);

            PageInfo<PractitionerLeadsGoalsInfo> pageInfo = new PageInfo<>(list);

            // 设置resp
            resp.setList(pageInfo.getList());
            pageInfo.setList(null);
            resp.setPage(pageInfo);

            resp.setCommonResult(new CommonResult(true, ZHBErrorConfig.getErrorInfo("800000")));
        } catch (Exception e) {
            e.printStackTrace();
            resp.setCommonResult(new CommonResult(false, e.getMessage()));
        }
        return resp;
    }

    @Override
    public CommonResultResponseVO practitionerLeadsGoalsExport(PractitionerLeadsGoalsRequestVO requestVO, HttpServletResponse response) {
        CommonResultResponseVO resp = new CommonResultResponseVO();
        List<Map<String, Object>> dataList = agmsPractitionerDALService.practitionerLeadsGoalsExport(requestVO);

        String[] columnName = new String[]{"序号", "经纪人姓名", "目标类型", "设置年份或月份", "保费", "佣金", "件数", "件均保费", "设置时间"};
        String tableName = "PractitionerLeadsGoals" + System.currentTimeMillis() + ".csv";

        this.exportCSV(tableName, columnName, dataList, response);

        resp.setCommonResult(new CommonResult(true, ZHBErrorConfig.getErrorInfo("800000")));
        return resp;
    }

    @Override
    public PractitionerActivityResponseVO practitionerActivity(PractitionerActivityRequestVO requestVO) {
        PractitionerActivityResponseVO resp = new PractitionerActivityResponseVO();

        List<PractitionerActivityInfo> list;
        try {
            PageInfo<PractitionerActivityInfo> page = requestVO.getPage();
            PageHelper.startPage(page.getPageNum(), page.getPageSize(), null);

            list = agmsPractitionerDALService.practitionerActivity(requestVO);

            PageInfo<PractitionerActivityInfo> pageInfo = new PageInfo<>(list);

            // 设置resp
            resp.setList(pageInfo.getList());
            pageInfo.setList(null);
            resp.setPage(pageInfo);

            resp.setCommonResult(new CommonResult(true, ZHBErrorConfig.getErrorInfo("800000")));
        } catch (Exception e) {
            e.printStackTrace();
            resp.setCommonResult(new CommonResult(false, e.getMessage()));
        }
        return resp;
    }

    @Override
    public CommonResultResponseVO practitionerActivityExport(PractitionerActivityRequestVO requestVO, HttpServletResponse response) {
        CommonResultResponseVO resp = new CommonResultResponseVO();
        List<Map<String, Object>> dataList = agmsPractitionerDALService.practitionerActivityExport(requestVO);

        String[] columnName = new String[]{"序号", "经纪人", "活动量类型", "活动量分值", "日期"};
        String tableName = "PractitionerActivity" + System.currentTimeMillis() + ".csv";

        this.exportCSV(tableName, columnName, dataList, response);

        resp.setCommonResult(new CommonResult(true, ZHBErrorConfig.getErrorInfo("800000")));
        return resp;
    }

    private void exportCSV(String tableName, String[] columnName, List<Map<String, Object>> dataList, HttpServletResponse response) {
//        String[] columnName = new String[]{"序号", "经纪人姓名", "日期", "日程类型", "日程内容", "任务开始时间", "任务结束时间", "备注", "设置时间"};
//        String tableName = "PractitionerSchedule" + System.currentTimeMillis() + ".csv";

        String CSV_COLUMN_SEPARATOR = ",";//CSV文件列分隔符
        String CSV_ROW_SEPARATOR = "\r\n";//CSV文件行分隔符
        // 保证线程安全
        StringBuilder buf = new StringBuilder();
        // 组装表头
        for (String title : columnName) {
            buf.append(title).append(CSV_COLUMN_SEPARATOR);
        }
        buf.append(CSV_ROW_SEPARATOR);
        // 组装数据
        if (CollectionUtils.isNotEmpty(dataList)) {
            Map<String, Object> map = null;
            for (int i = 0; i < dataList.size(); i++) {
                map = dataList.get(i);//遍历每个对象
                // 序号
                buf.append(i + 1).append(CSV_COLUMN_SEPARATOR);

                for (int j = 1; j < columnName.length; j++) {
                    buf.append(map.get(j + "") == null ? "" : map.get(j + "")).append("\t").append(CSV_COLUMN_SEPARATOR);
                }

                buf.append(CSV_ROW_SEPARATOR);
            }
        }
        // 设置文件后缀
        setCSVResponse(response, tableName, buf);
    }

    private void setCSVResponse(HttpServletResponse response, String fn, StringBuilder data) {
        String charset = "UTF-8"; // 读取字符编码
//        String fn = tableName + System.currentTimeMillis()  + ".csv";
        String headStr = "attachment; filename=\"" + fn + "\"";
        // 设置响应
        response.setContentType("APPLICATION/ms-csv.numberformat");
        response.setCharacterEncoding(charset);
        response.setHeader("Content-Disposition", headStr);
        response.setHeader("Cache-Control", "max-age=30");
        response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
        response.setHeader("Pragma", "public");
        OutputStream os = null;
        try {
            os = response.getOutputStream();
            os.write(data.toString().getBytes("GBK"));
            os.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
