package com.cftech.report.web;

import com.alibaba.fastjson.JSONObject;
import com.cftech.report.model.Report;

import com.cftech.core.poi.ExcelKit;
import com.cftech.core.scope.OrderType;
import com.cftech.core.sql.Conds;
import com.cftech.core.sql.Sort;
import com.cftech.core.util.Constants;
import com.cftech.report.service.ReportService;
import com.cftech.sys.security.PermissionSign;
import com.cftech.sys.security.UserUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.List;


/**
 * 报表信息Controller
 * <p>
 * 权限字符串说明:
 * 查看:public static final String REPORT_VIEW = "qy:report:view"
 * 查看:public static final String REPORT_EDIT = "qy:report:edit"
 *
 * @author Buyj
 * @date: 2020-12-02 11:26
 */
@Slf4j
@Controller
@RequestMapping("/a/report")
public class ReportController {

    public static final String REPORT_VIEW = "qy:report:view";
    public static final String REPORT_EDIT = "qy:report:edit";

    @Autowired
    private ReportService reportService;


    //列表页面
    @RequiresPermissions(value = REPORT_VIEW)
    @RequestMapping("/list")
    public String list(HttpServletRequest request, Model model) {
        Long accountId = UserUtils.getmpaccounts(request);
        model.addAttribute("accountId", accountId);
        return "report/reportlist";
    }

    //编辑页面（新增、修改）
    @RequiresPermissions(value = REPORT_VIEW)
    @RequestMapping("/form")
    public String form(HttpServletRequest request, String id, Model model) {
        if (!StringUtils.isEmpty(id)) {
            Report report = reportService.fetchById(id);
            model.addAttribute("data", report);
        }
        return "report/reportform";
    }

    //提交数据（新增、修改）
    @RequiresPermissions(value = REPORT_EDIT)
    @RequestMapping("/formData")
    @ResponseBody
    public JSONObject formData(Report report, Model model, HttpServletRequest request) {
        Long accountsId = UserUtils.getmpaccounts(request);
        JSONObject rtnJson = new JSONObject();
        try {
            if (report != null && report.getId() != null) {
                report.setUpdateBy(UserUtils.getUser().getId());
                reportService.update(report);
                rtnJson.put("errorNo", 0);
            } else {
                report.setAccountsId(accountsId);
                report.setDelFlag(false);
                report.setAccountsId(UserUtils.getmpaccounts(request));
                report.setCreateBy(UserUtils.getUser().getId());
                report.setUpdateBy(UserUtils.getUser().getId());
                reportService.save(report);
                rtnJson.put("errorNo", 2);
            }
        } catch (Exception e) {
            rtnJson.put("errorNo", 1);
        }
        return rtnJson;
    }

    //获取列表数据
    @RequiresPermissions(value = REPORT_VIEW)
    @RequestMapping(value = "/listData")
    @ResponseBody
    public JSONObject listData(int iDisplayStart, int iDisplayLength, Report report, HttpServletRequest request,String startPayTime,String endPayTime) {
        Long accountsId = UserUtils.getmpaccounts(request);
        Conds conds = new Conds();
        conds.equal("del_flag", Constants.DEL_FLAG_0);
        //conds.equal("accounts_id", accountsId);
        Sort sort = new Sort("create_time", OrderType.DESC);

        if(!StringUtils.isEmpty(report.getRegion())){
            conds.like("region",report.getRegion());
        }

        if(!StringUtils.isEmpty(report.getProvince())){
            conds.like("province",report.getProvince());
        }

        if(!StringUtils.isEmpty(report.getCity())){
            conds.like("city",report.getCity());
        }

        if(!StringUtils.isEmpty(report.getHospital())){
            conds.like("hospital",report.getHospital());
        }

        if(!StringUtils.isEmpty(report.getDoctorName())){
            conds.like("doctor_name",report.getDoctorName());
        }

        if(!StringUtils.isEmpty(report.getPhone())){
            conds.like("phone",report.getPhone());
        }

        if(!StringUtils.isEmpty(report.getDrugsNum())){
            conds.equal("drugs_num",report.getDrugsNum());
        }

        if(!StringUtils.isEmpty(startPayTime)){
            conds.greatEqual("DATE_FORMAT(fk_time,'%Y-%m-%d')",startPayTime);
        }

        if(!StringUtils.isEmpty(endPayTime)){
            conds.lessEqual("DATE_FORMAT(fk_time,'%Y-%m-%d')",endPayTime);
        }


        List<Report> list = reportService.fetchSearchByPage(conds, sort, iDisplayStart, iDisplayLength);
        Integer counts = reportService.count(conds);
        JSONObject rtnJson = new JSONObject();
        rtnJson.put("iTotalRecords", counts);
        rtnJson.put("iTotalDisplayRecords", counts);
        rtnJson.put("aaData", list);
        return rtnJson;
    }

    //删除数据
    @RequiresPermissions(value = REPORT_EDIT)
    @RequestMapping("/delete")
    @ResponseBody
    public JSONObject delete(String id) {
        JSONObject rtnJosn = new JSONObject();
        try {
            reportService.delete(id);
            rtnJosn.put("errorNo", 0);
        } catch (Exception e) {
            rtnJosn.put("errorNo", 1);
        }
        return rtnJosn;
    }

    @RequestMapping("/exportExcel")
    @RequiresPermissions(value = REPORT_VIEW)
    public void exportExcel(Report report, HttpServletRequest request,String startPayTime,String endPayTime, HttpServletResponse response) {
        Long accountId = UserUtils.getmpaccounts(request);
        Sort sort = new Sort("create_time", OrderType.ASC);
        Conds conds = new Conds();
        conds.equal("del_flag", 0);
        if(!StringUtils.isEmpty(report.getRegion())){
            conds.like("region",report.getRegion());
        }

        if(!StringUtils.isEmpty(report.getProvince())){
            conds.like("province",report.getProvince());
        }

        if(!StringUtils.isEmpty(report.getCity())){
            conds.like("city",report.getCity());
        }

        if(!StringUtils.isEmpty(report.getHospital())){
            conds.like("hospital",report.getHospital());
        }

        if(!StringUtils.isEmpty(report.getDoctorName())){
            conds.like("doctor_name",report.getDoctorName());
        }

        if(!StringUtils.isEmpty(report.getPhone())){
            conds.like("phone",report.getPhone());
        }

        if(!StringUtils.isEmpty(report.getDrugsNum())){
            conds.equal("drugs_num",report.getDrugsNum());
        }

        if(!StringUtils.isEmpty(startPayTime)){
            conds.greatEqual("DATE_FORMAT(fk_time,'%Y-%m-%d')",startPayTime);
        }

        if(!StringUtils.isEmpty(endPayTime)){
            conds.lessEqual("DATE_FORMAT(fk_time,'%Y-%m-%d')",endPayTime);
        }
        List<Report> list = reportService.fetchSearchByPage(conds, sort, 0, 0);
        ExcelKit.$Export(Report.class, response).toExcel(list, "报表信息信息");
    }

    @RequestMapping("/templateExcel")
    @RequiresPermissions(value = REPORT_VIEW)
    public void templateExcel(HttpServletRequest request, HttpServletResponse response) {
        ExcelKit.$Export(Report.class, response).toExcel(null, "报表信息信息");
    }

    @RequestMapping("/importExcel")
    @RequiresPermissions(value = REPORT_EDIT)
    public String importExcel(HttpServletRequest request, MultipartFile file, Model model) {
        Long accountId = UserUtils.getmpaccounts(request);
        if (file == null) {
            return list(request, model);
        }
// 构造临时路径来存储上传的文件
        String uploadPath = System.getProperty("java.io.tmpdir");
        File uploadDir = new File(uploadPath);
        if (!uploadDir.exists()) {
            uploadDir.mkdir();
        }
        String fileName = file.getOriginalFilename();
        String filePath = uploadPath + File.separator + fileName;
        File storeFile = new File(filePath);
        try {
            file.transferTo(storeFile);
            ExcelKit.$Import().setEmptyCellValue("").readExcel(storeFile, rowData -> {
                if (!StringUtils.isEmpty(rowData.get(0))) {
                    Report report = new Report();
                    report.setAccountsId(accountId);
                    reportService.save(report);
                }
            });
        } catch (IOException e) {
            log.error(e.getMessage());
        }

        return list(request, model);
    }

}
