package com.cftech.consultsheet.web;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cftech.consultsheet.model.ConsultSheet;
import com.cftech.consultsheet.model.ConsultSheetVO;
import com.cftech.consultsheet.service.ConsultSheetService;
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.sys.model.User;
import com.cftech.sys.security.UserUtils;
import org.springframework.util.StringUtils;
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.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
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.LinkedList;
import java.util.List;


/**
 * 咨询单Controller
 * <p>
 * 权限字符串说明:
 * 查看:public static final String CONSULTSHEET_VIEW = "qy:consultSheet:view"
 * 查看:public static final String CONSULTSHEET_EDIT = "qy:consultSheet:edit"
 *
 * @author licc
 * @date: 2020-09-22 12:06
 */
@Slf4j
@Controller
@RequestMapping("/a/consultSheet")
public class ConsultSheetController {

    public static final String CONSULTSHEET_VIEW = "qy:consultSheet:view";
    public static final String CONSULTSHEET_EDIT = "qy:consultSheet:edit";

    @Autowired
    private ConsultSheetService consultSheetService;


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

    //编辑页面（新增、修改）
    @RequiresPermissions(value = CONSULTSHEET_VIEW)
    @RequestMapping("/form")
    public String form(HttpServletRequest request, String id, Model model) {
        if (!StringUtils.isEmpty(id)) {
            ConsultSheet consultSheet = consultSheetService.fetchById(id);
            JSONObject object= JSON.parseObject(JSON.toJSONString(consultSheet));
            model.addAttribute("data", object);
        }
        return "consultSheet/consultSheetform";
    }

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

    //审核拒绝功能
    @RequestMapping(value = "/updateData")
    @ResponseBody
    public JSONObject updateData( String consultId, String status,String description ,HttpServletRequest request) {
        JSONObject rtnJson = new JSONObject();
        Conds conds = new Conds();
        try {
            if (!StringUtils.isEmpty(consultId) && !StringUtils.isEmpty(status) && !StringUtils.isEmpty(description)) {
                Integer integer = consultSheetService.updateDate(consultId, status, description);
                if (integer>0){
                    rtnJson.put("errorNo", 1);
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
            rtnJson.put("errorNo", 0);
        }
        return rtnJson;
    }
    //审核通过功能
    @RequiresPermissions(value = CONSULTSHEET_EDIT)
    @RequestMapping("/updateStatus")
    @ResponseBody
    public JSONObject updateStatus(String consultId, String status, HttpServletRequest request) {
        JSONObject rtnJson = new JSONObject();
        Conds conds = new Conds();
        try {
            if (!StringUtils.isEmpty(consultId) && !StringUtils.isEmpty(status) ) {
                Integer integer = consultSheetService.updateStatus(consultId, status);
                if (integer>0){
                    rtnJson.put("errorNo", 1);
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
            rtnJson.put("errorNo", 0);
        }
        return rtnJson;
    }

    //获取列表数据
    @RequiresPermissions(value = CONSULTSHEET_VIEW)
    @RequestMapping(value = "/listData")
    @ResponseBody
    public JSONObject listData(int iDisplayStart, int iDisplayLength, ConsultSheet consultSheet, HttpServletRequest request) {
        String id = String.valueOf(UserUtils.getUser().getId());

        Long accountsId = UserUtils.getmpaccounts(request);
        Conds conds = new Conds();

        if (!StringUtils.isEmpty(consultSheet.getUserName())){
            conds.like("a.user_name",consultSheet.getUserName());
        }
        if (!StringUtils.isEmpty(consultSheet.getIllness())){
            conds.like("a.illness",consultSheet.getIllness());
        }

        conds.equal("a.del_flag", Constants.DEL_FLAG_0);
        conds.equal("a.accounts_id", accountsId);
        Sort sort = new Sort("a.create_time", OrderType.DESC);

        List<ConsultSheet> list = consultSheetService.fetchSearchBy(conds, sort, iDisplayStart, iDisplayLength,id);
        Integer counts = consultSheetService.count(conds);
        JSONObject rtnJson = new JSONObject();
        rtnJson.put("iTotalRecords", counts);
        rtnJson.put("iTotalDisplayRecords", counts);
        rtnJson.put("aaData", list);
        System.out.println(rtnJson.toJSONString());
        return rtnJson;
    }

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

    @RequestMapping("/exportExcel")
    @RequiresPermissions(value = CONSULTSHEET_VIEW)
    public void exportExcel(HttpServletRequest request, HttpServletResponse response) {
        Long accountId = UserUtils.getmpaccounts(request);
        Sort sort = new Sort("a.create_time", OrderType.ASC);
        Conds conds = new Conds();
        conds.equal("a.del_flag", 0);

        List<ConsultSheet> list = consultSheetService.fetchSearchByPage(conds, sort, 0, 0);
        List<ConsultSheetVO> consultSheetVOS = new LinkedList<>();
        for (ConsultSheet consultSheet : list) {
            ConsultSheetVO consultSheetVO = new ConsultSheetVO();
            consultSheetVO.setConsultId(consultSheet.getConsultId());
            consultSheetVO.setUserName(consultSheet.getUserName());
            consultSheetVO.setSex(consultSheet.getSex() == 1 ? "男" : "女");
            consultSheetVO.setPhone(consultSheet.getIPhone());
            consultSheetVO.setPastRecords(consultSheet.getPastRecords());
            consultSheetVO.setIllness(consultSheet.getIllness());
            consultSheetVO.setAllergy(consultSheet.getAllergy());
            consultSheetVO.setStatus(consultSheet.getStatus().equals("0") ? "未审核" : consultSheet.getStatus().equals("1") ? "已通过" : "已拒绝");
            consultSheetVO.setPharmaName(consultSheet.getPharmaName());
            consultSheetVO.setCustomerName(consultSheet.getCustomerName());
            consultSheetVOS.add(consultSheetVO);
        }
        ExcelKit.$Export(ConsultSheetVO.class, response).toExcel(consultSheetVOS, "咨询单信息");
    }

    @RequestMapping("/templateExcel")
    @RequiresPermissions(value = CONSULTSHEET_VIEW)
    public void templateExcel(HttpServletRequest request, HttpServletResponse response) {
        ExcelKit.$Export(ConsultSheet.class, response).toExcel(null, "咨询单信息");
    }

    @RequestMapping("/importExcel")
    @RequiresPermissions(value = CONSULTSHEET_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))) {
                    ConsultSheet consultSheet = new ConsultSheet();
                    consultSheet.setAccountsId(accountId);
                    consultSheetService.save(consultSheet);
                }
            });
        } catch (IOException e) {
            log.error(e.getMessage());
        }

        return list(request, model);
    }

}
