package com.yihu.wlyy.web.common.qrcode;

import com.yihu.wlyy.entity.doctor.profile.Doctor;
import com.yihu.wlyy.service.common.QrcodeService;
import com.yihu.wlyy.service.common.account.DoctorService;
import com.yihu.wlyy.web.WeixinBaseController;
import io.swagger.annotations.Api;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * Created by lyr on 2016/08/10.
 */
@Controller
@RequestMapping(value = "/qrcode", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@Api(description = "二维码")
public class QrCodeController extends WeixinBaseController {

    @Autowired
    private QrcodeService qrcodeService;
    @Autowired
    private DoctorService doctorService;

    @RequestMapping(value = "/doctors")
    @ResponseBody
    public String makeDoctorQrcodes(String hospital) {
        try {
            if (qrcodeService.makeDoctorQrCode(hospital, getAccessToken())) {
                return write(200, "生成二维码成功!");
            } else {
                return error(-1, "生成二维码失败!");
            }
        } catch (Exception e) {
            return error(-1, "生成二维码失败!");
        }
    }

    /**
     * 生成某个医生的二维码
     *
     * @param doctor
     * @return
     */
    @RequestMapping(value = "/doctor")
    @ResponseBody
    public String makeDoctorQrcode(String doctor) {
        try {
            if (qrcodeService.makeDoctorQrcode(doctor, getAccessToken())) {
                return write(200, "生成二维码成功!");
            } else {
                return error(-1, "生成二维码失败!");
            }
        } catch (Exception e) {
            return error(-1, "生成二维码失败!");
        }
    }

    /**
     * 生成社区二维码
     *
     * @param hospital
     * @return
     */
    @RequestMapping(value = "/hospital")
    @ResponseBody
    public String makeHospitalQrcode(String hospital) {
        try {
            if (qrcodeService.makeHospitalQrcode(hospital, getAccessToken())) {
                return write(200, "生成二维码成功!");
            } else {
                return error(-1, "生成二维码失败!");
            }
        } catch (Exception e) {
            return error(-1, "生成二维码失败!");
        }
    }

    /**
     * 生成区二维码
     *
     * @param town
     * @return
     */
    @RequestMapping(value = "/town")
    @ResponseBody
    public String makeTownQrcode(String town) {
        try {
            if (qrcodeService.makeTownQrcode(town, getAccessToken())) {
                return write(200, "生成二维码成功!");
            } else {
                return error(-1, "生成二维码失败!");
            }
        } catch (Exception e) {
            return error(-1, "生成二维码失败!");
        }
    }


    /**
     * 下载某个社区的二维码
     *
     * @param hospital
     * @param response
     */
    @RequestMapping(value = "/hospital_img")
    public void downloadSqQrcode(String hospital, HttpServletResponse response) {
        try {
            File file = new File(QrCodeController.class.getResource("/").getPath().replace("/WEB-INF/classes/", "") +
                    File.separator + "qrcode" + File.separator + hospital + ".png");
            boolean flag = false;
            if (!file.exists()) {
                flag = qrcodeService.makeHospitalQrcode(hospital, getAccessToken());
            } else {
                flag = true;
            }

            if (flag = true) {
                response.setCharacterEncoding("utf-8");

                String path = request.getSession().getServletContext().getRealPath("/")
                        + File.separator + "qrcode" + File.separator + hospital + ".png";
                InputStream inputStream = new FileInputStream(path);
                OutputStream outputStream = response.getOutputStream();
                byte[] b = new byte[2048];
                int length = 0;

                while ((length = inputStream.read(b)) > 0) {
                    outputStream.write(b, 0, length);
                }
                outputStream.flush();
                outputStream.close();
                inputStream.close();
            } else {
                response.setStatus(404);
            }
        } catch (Exception e) {

        }
    }

    /**
     * 下载某个区的二维码
     *
     * @param town
     * @param response
     */
    @RequestMapping(value = "/town_img")
    public void downloadTownQrcode(String town, HttpServletResponse response) {
        try {
            File file = new File(QrCodeController.class.getResource("/").getPath().replace("/WEB-INF/classes/", "") +
                    File.separator + "qrcode" + File.separator + town + ".png");
            boolean flag = false;
            if (!file.exists()) {
                flag = qrcodeService.makeTownQrcode(town, getAccessToken());
            } else {
                flag = true;
            }

            if (flag = true) {
                response.setCharacterEncoding("utf-8");

                String path = request.getSession().getServletContext().getRealPath("/")
                        + File.separator + "qrcode" + File.separator + town + ".png";
                InputStream inputStream = new FileInputStream(path);
                OutputStream outputStream = response.getOutputStream();
                byte[] b = new byte[2048];
                int length = 0;

                while ((length = inputStream.read(b)) > 0) {
                    outputStream.write(b, 0, length);
                }
                outputStream.flush();
                outputStream.close();
                inputStream.close();
            } else {
                response.setStatus(404);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 下载某个医生的二维码
     *
     * @param doctor
     * @param response
     */
    @RequestMapping(value = "/download")
    public void downloadQrcode(String doctor, HttpServletResponse response) {
        try {
            Doctor doc = doctorService.findDoctorByCode(doctor);

            if (doc != null) {
                if (StringUtils.isEmpty(doc.getQrcode())) {
                    qrcodeService.makeDoctorQrcode(doctor, getAccessToken());
                    doc = doctorService.findDoctorByCode(doctor);
                } else {
                    File file = new File(QrCodeController.class.getResource("/").getPath().replace("/WEB-INF/classes/", "") +
                            File.separator + "qrcode" + File.separator + doc.getQrcode());

                    if (!file.exists()) {
                        qrcodeService.makeDoctorQrcode(doctor, getAccessToken());
                        doc = doctorService.findDoctorByCode(doctor);
                    }
                }

                response.setCharacterEncoding("utf-8");
                response.setContentType("multipart/form-data");
                response.setHeader("Content-Disposition", "attachment;fileName="
                        + doc.getQrcode());

                String path = request.getSession().getServletContext().getRealPath("/")
                        + File.separator + "qrcode" + File.separator + doc.getQrcode();
                InputStream inputStream = new FileInputStream(path);
                OutputStream outputStream = response.getOutputStream();
                byte[] b = new byte[2048];
                int length = 0;

                while ((length = inputStream.read(b)) > 0) {
                    outputStream.write(b, 0, length);
                }
                outputStream.flush();
                outputStream.close();
                inputStream.close();
            } else {
                throw new Exception("医生信息不存在!");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 下载某个医生的二维码
     *
     * @param doctor
     * @param response
     */
    @RequestMapping(value = "/doctor_img")
    public void downloadQrcodeImage(String doctor, HttpServletResponse response) {
        try {
            System.out.println("------------------doctor：" + doctor);
            Doctor doc = doctorService.findDoctorByCode(doctor);

            if (doc != null) {
                if (StringUtils.isEmpty(doc.getQrcode())) {
                    qrcodeService.makeDoctorQrcode(doctor, getAccessToken());
                    doc = doctorService.findDoctorByCode(doctor);
                } else {
                    File file = new File(QrCodeController.class.getResource("/").getPath().replace("/WEB-INF/classes/", "") +
                            File.separator + "qrcode" + File.separator + doc.getQrcode());

                    if (!file.exists()) {
                        qrcodeService.makeDoctorQrcode(doctor, getAccessToken());
                        doc = doctorService.findDoctorByCode(doctor);
                    }
                }
                String path = request.getSession().getServletContext().getRealPath("/")
                        + File.separator + "qrcode" + File.separator + doc.getQrcode();
                InputStream inputStream = new FileInputStream(path);
                response.setCharacterEncoding("utf-8");
                response.setContentType("multipart/form-data");
                response.setHeader("Content-Disposition", "attachment;fileName=" + doc.getQrcode());
                OutputStream outputStream = response.getOutputStream();
                byte[] b = new byte[2048];
                int length = 0;

                while ((length = inputStream.read(b)) > 0) {
                    outputStream.write(b, 0, length);
                }
                outputStream.flush();
                outputStream.close();
                inputStream.close();
            } else {
                throw new Exception("医生信息不存在!");
            }
        } catch (Exception e) {
            response.setStatus(500);
        }
    }

    /**
     * 下载所有医生的二维码图片
     *
     * @param hospital
     * @param response
     */
    @RequestMapping(value = "/download/doctors")
    public void downloadQrcodes(String hospital, HttpServletResponse response) {
        try {
            File file = qrcodeService.downloadDoctorQrCodes(hospital, getAccessToken());

            if (file != null) {
                response.setCharacterEncoding("utf-8");
                response.setContentType("multipart/form-data");
                response.setHeader("Content-Disposition", "attachment;fileName=doctors_qrcode.zip");

                InputStream inputStream = new FileInputStream(file);
                OutputStream outputStream = response.getOutputStream();
                byte[] b = new byte[2048];
                int length = 0;

                while ((length = inputStream.read(b)) > 0) {
                    outputStream.write(b, 0, length);
                }
                outputStream.flush();
                outputStream.close();
                inputStream.close();
            } else {
                response.setStatus(500);
            }
        } catch (Exception e) {
            response.setStatus(500);
        }
    }

    /**
     * 下载某个区的社区的二维码图片
     *
     * @param area
     * @param response
     */
    @RequestMapping(value = "/download/hospitals")
    public void downloadSqQrcodes(String area, HttpServletResponse response) {
        try {
            File file = qrcodeService.downloadHospitalQrCodes(area, getAccessToken());

            if (file != null) {
                response.setCharacterEncoding("utf-8");
                response.setContentType("multipart/form-data");
                response.setHeader("Content-Disposition", "attachment;fileName=hospitals_qrcode.zip");

                InputStream inputStream = new FileInputStream(file);
                OutputStream outputStream = response.getOutputStream();
                byte[] b = new byte[2048];
                int length = 0;

                while ((length = inputStream.read(b)) > 0) {
                    outputStream.write(b, 0, length);
                }
                outputStream.flush();
                outputStream.close();
                inputStream.close();
            } else {
                response.setStatus(500);
            }
        } catch (Exception e) {
            response.setStatus(500);
        }
    }

    /**
     * 下载某个城市的区的二维码图片
     *
     * @param city
     * @param response
     */
    @RequestMapping(value = "/download/towns")
    public void downloadTownQrcodes(String city, HttpServletResponse response) {
        try {
            File file = qrcodeService.downLoadTownQrcodes(city, getAccessToken());

            if (file != null) {
                response.setCharacterEncoding("utf-8");
                response.setContentType("multipart/form-data");
                response.setHeader("Content-Disposition", "attachment;fileName=towns_qrcode.zip");

                InputStream inputStream = new FileInputStream(file);
                OutputStream outputStream = response.getOutputStream();
                byte[] b = new byte[2048];
                int length = 0;

                while ((length = inputStream.read(b)) > 0) {
                    outputStream.write(b, 0, length);
                }
                outputStream.flush();
                outputStream.close();
                inputStream.close();
            } else {
                response.setStatus(500);
            }
        } catch (Exception e) {
            response.setStatus(500);
        }
    }

}
