package com.cftech.consultsheet.web;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cftech.accounts.service.MpAccountsService;
import com.cftech.addresst.model.Address;
import com.cftech.addresst.service.AddressService;
import com.cftech.base.codingrule.utils.CodingruleUtils;
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.core.util.DateFormatUtils;
import com.cftech.core.util.MpTokenUtil;
import com.cftech.core.util.SystemConfig;
import com.cftech.order.model.Order;
import com.cftech.order.service.OrderService;
import com.cftech.sys.security.UserUtils;
import com.google.gson.Gson;
import org.mp.api.core.req.model.message.IndustryTemplateMessageSend;
import org.mp.api.core.req.model.message.TemplateData;
import org.mp.api.wxsendmsg.JwTemplateMessageAPI;
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.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;

    @Autowired
    private MpAccountsService mpAccountsService;

    @Autowired
    private MpTokenUtil mpTokenUtil;

    @Autowired
    private OrderService orderService;

    @Autowired
    private CodingruleUtils codingruleUtils;

    @Autowired
    private AddressService addressService;


    //列表页面
    @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();
        ConsultSheet consultSheet = consultSheetService.fetchById(Long.parseLong(consultId));
        try {
            if (!StringUtils.isEmpty(consultId) && !StringUtils.isEmpty(status) && !StringUtils.isEmpty(description)) {
                Integer integer = consultSheetService.updateDate(consultId, status, description);
                if (integer>0) {
                    //发送审核通过模板消息
                    String appid = SystemConfig.p.getProperty("WX_MP_SERVER_APPID");
                    String refuseTmpId = SystemConfig.p.getProperty("CONSULT_SHEET_AUDIT_REFUSE_TEMPLATE_MSG");
                    String token = mpTokenUtil.getToken(mpAccountsService.getMpAccountsAppid(appid));
                    String first = "您好，您的咨询单审核不通过。";
                    String remark = "不通过原由：{" + consultSheet.getDescription() + "};请点击详情重新填写咨询单。";

                    String [] keywords = {consultSheet.getUserName(),
                            consultSheet.getConsultId(),
                            DateFormatUtils.getDateFormat(consultSheet.getCreateTime(), "yyyy年MM月dd日")};

                    sendMessage(refuseTmpId, token, consultSheet.getOpenId(),first, remark, keywords, null);
                    rtnJson.put("errorNo", 0);
                }
            }
        } catch (Exception e) {
            //发送审核通过模板消息
            String appid = SystemConfig.p.getProperty("WX_MP_SERVER_APPID");
            String refuseTmpId = SystemConfig.p.getProperty("CONSULT_SHEET_AUDIT_SUCCESS_TEMPLATE_MSG");
            String token = mpTokenUtil.getToken(mpAccountsService.getMpAccountsAppid(appid));
            String first = "您好，您提交的咨询单审核失败。";
            String remark = "请重新填写咨询单。";

            String [] keywords = {consultSheet.getUserName(),
                    consultSheet.getConsultId(),
                    DateFormatUtils.getDateFormat(consultSheet.getCreateTime(), "yyyy年MM月dd日")};
            sendMessage(refuseTmpId, token, consultSheet.getOpenId(),first, remark, keywords, null);

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

                    //生成空订单
                    Order order = new Order();
                    order.setNumber(codingruleUtils.getNumber(consultSheet.getAccountsId(), Order.class.getName()));
                    order.setOpenid(consultSheet.getOpenId());
                    order.setConsultId(consultSheet.getId());
                    order.setServiceId(consultSheet.getServiceId());
                    order.setDoctorId(consultSheet.getDoctorId());


                    //获取默认地址
                    Conds adsConds = new Conds();
                    adsConds.equal("t.del_flag", Constants.DEL_FLAG_0);
                    adsConds.equal("t.open_id", consultSheet.getOpenId());
                    adsConds.equal("t.whether", "1");
                    Address address = addressService.fetchSearchByConds(adsConds);
                    if (address != null) {
                        order.setAddressId(address.getId());
                    }
                    orderService.save(order);

                    //反写咨询单
                    consultSheet.setOrderId(order.getId());
                    consultSheetService.update(consultSheet);


                    //发送审核通过模板消息
                    String appid = SystemConfig.p.getProperty("WX_MP_SERVER_APPID");
                    String refuseTmpId = SystemConfig.p.getProperty("CONSULT_SHEET_AUDIT_SUCCESS_TEMPLATE_MSG");
                    String token = mpTokenUtil.getToken(mpAccountsService.getMpAccountsAppid(appid));
                    String first = "您好，您的咨询单已完成。";
                    String remark = "请点击详情查看咨询单信息。";

                    String [] keywords = {consultSheet.getUserName(),
                                        order.getNumber()};
                    sendMessage(refuseTmpId, token, consultSheet.getOpenId(),first, remark, keywords, null);

                    rtnJson.put("errorNo", 0);
                }
            }
        } catch (Exception e) {
            //发送审核通过模板消息
            String appid = SystemConfig.p.getProperty("WX_MP_SERVER_APPID");
            String refuseTmpId = SystemConfig.p.getProperty("CONSULT_SHEET_AUDIT_SUCCESS_TEMPLATE_MSG");
            String token = mpTokenUtil.getToken(mpAccountsService.getMpAccountsAppid(appid));
            String first = "您好，您提交的咨询单审核失败。";
            String remark = "请重新填写咨询单。";

            String [] keywords = {consultSheet.getUserName(),
                    consultSheet.getConsultId(),
                    DateFormatUtils.getDateFormat(consultSheet.getCreateTime(), "yyyy年MM月dd日")};
            sendMessage(refuseTmpId, token, consultSheet.getOpenId(),first, remark, keywords, null);

            e.printStackTrace();
            rtnJson.put("errorNo", 1);
        }
        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.getPhone());
            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);
    }

    private void sendMessage(String templateId, String token, String openId, String first, String remark, String [] keywords, String url){
        IndustryTemplateMessageSend mc = new IndustryTemplateMessageSend();
        mc.setTemplate_id(templateId);
        mc.setTouser(openId);
        mc.setAccess_token(token);
        mc.setUrl(url);
        StringBuffer json = new StringBuffer();
        Gson gson = new Gson();
        String objJson = gson.toJson(mc);
        json.append(objJson);
        json.setLength(json.length()-1);
        json.append(",");
        json.append("\"data\":{");
        TemplateData template = new TemplateData();
        template.setValue(first);
        //template.setColor("#ffAADD");
        objJson = gson.toJson(template);
        json.append(" \"first\":");
        json.append(objJson);
        json.append(",");
        if(keywords!=null && keywords.length>0){
            for(int i=0;i<keywords.length;i++){
                template.setValue(keywords[i]);
                objJson = gson.toJson(template);
                json.append(" \"keyword"+(i+1)+"\":");
                json.append(objJson);
                json.append(",");
            }
        }
        template.setValue(remark);
        objJson = gson.toJson(template);
        json.append(" \"remark\":");
        json.append(objJson);
        json.append("}}");
        JwTemplateMessageAPI.sendTemplateMsgJson(json.toString(),token);
    }
}
