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.*;
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 lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;

import org.owasp.esapi.ESAPI;
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 org.springframework.web.util.HtmlUtils;

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";
    }

    //跳转订单列表
    @RequestMapping("/orderlist")
    public String orderlist(HttpServletRequest request, Model model, String orderCode) {
        Long accountId = UserUtils.getmpaccounts(request);
        model.addAttribute("accountId", accountId);
        model.addAttribute("orderCode", orderCode);
        return "order/orderlist";
    }

    //编辑页面（新增、修改）
    @RequiresPermissions(value = CONSULTSHEET_VIEW)
    @RequestMapping("/form")
    public String form(String pageType, String id, Model model) {
        if (StringUtils.isNoneBlank(id)) {
            ConsultSheet consultSheet = consultSheetService.fetchById(id);
            if (StringUtils.isNoneBlank(consultSheet.getUserName()) && consultSheet.getUserName().length() >=2) {
                StringBuilder str = new StringBuilder(consultSheet.getUserName());
                str.replace(1, 2, "*");
                consultSheet.setUserName(str.toString());
            }
            if (StringUtils.isNoneBlank(consultSheet.getPhone())) {
                StringBuilder str = new StringBuilder(consultSheet.getPhone());
                str.replace(3, 7, "****");
                consultSheet.setPhone(str.toString());
            }
            JSONObject object = JSON.parseObject(JSON.toJSONString(consultSheet));
            model.addAttribute("data", object);
            model.addAttribute("isView", pageType.equals("View") ? true : false);//是否查看页面
        }
        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;
    }

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

        Long accountsId = UserUtils.getmpaccounts(request);
        Conds conds = new Conds();
        conds.equal("a.del_flag", Constants.DEL_FLAG_0);
        conds.equal("a.accounts_id", accountsId);
        if (StringUtils.isNoneBlank(consultSheet.getConsultId())) {
            conds.like("a.consult_id", "%" + consultSheet.getConsultId() + "%");
        }
        if (StringUtils.isNoneBlank(consultSheet.getStartCreateTime())) {
            conds.greatEqual("DATE_FORMAT(a.create_time, '%Y-%m-%d')", consultSheet.getStartCreateTime());
        }
        if (StringUtils.isNoneBlank(consultSheet.getEndCreateTime())) {
            conds.lessEqual("DATE_FORMAT(a.create_time, '%Y-%m-%d')", consultSheet.getEndCreateTime());
        }
        if (StringUtils.isNoneBlank(consultSheet.getStartAuditTime())) {
            conds.greatEqual("DATE_FORMAT(a.audit_time, '%Y-%m-%d')", consultSheet.getStartAuditTime());
        }
        if (StringUtils.isNoneBlank(consultSheet.getEndAuditTime())) {
            conds.lessEqual("DATE_FORMAT(a.audit_time, '%Y-%m-%d')", consultSheet.getEndAuditTime());
        }

        Sort sort = new Sort("a.create_time", OrderType.DESC);

        List<ConsultSheet> list = consultSheetService.fetchSearchBy(conds, sort, iDisplayStart, iDisplayLength, id);
        Integer counts = consultSheetService.fetchSearchByCount(conds, id);
        JSONObject rtnJson = new JSONObject();
        rtnJson.put("iTotalRecords", counts);
        rtnJson.put("iTotalDisplayRecords", counts);
        rtnJson.put("aaData", list);
        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, ConsultSheet consultSheet) {
        Long accountId = UserUtils.getmpaccounts(request);
        Sort sort = new Sort("a.create_time", OrderType.ASC);
        Conds conds = new Conds();
        if (StringUtils.isNoneBlank(consultSheet.getConsultId())) {
            conds.like("a.consult_id", "%" + consultSheet.getConsultId() + "%");
        }
        if (StringUtils.isNoneBlank(consultSheet.getStartCreateTime())) {
            conds.greatEqual("DATE_FORMAT(a.create_time, '%Y-%m-%d')", consultSheet.getStartCreateTime());
        }
        if (StringUtils.isNoneBlank(consultSheet.getEndCreateTime())) {
            conds.lessEqual("DATE_FORMAT(a.create_time, '%Y-%m-%d')", consultSheet.getEndCreateTime());
        }
        if (StringUtils.isNoneBlank(consultSheet.getStartAuditTime())) {
            conds.greatEqual("DATE_FORMAT(a.audit_time, '%Y-%m-%d')", consultSheet.getStartAuditTime());
        }
        if (StringUtils.isNoneBlank(consultSheet.getEndAuditTime())) {
            conds.lessEqual("DATE_FORMAT(a.audit_time, '%Y-%m-%d')", consultSheet.getEndAuditTime());
        }
        conds.equal("a.del_flag", Constants.DEL_FLAG_0);
        conds.equal("a.accounts_id", accountId);

        List<ConsultSheet> list = consultSheetService.fetchSearchByPage(conds, sort, 0, 0);
        List<ConsultSheetVO> consultSheetVOS = new LinkedList<>();
        ConsultSheetVO consultSheetVO = null;
        for (ConsultSheet consultSheetObj : list) {
            consultSheetVO = new ConsultSheetVO();
            consultSheetVO.setOrderCode(consultSheetObj.getOrderCode());
            consultSheetVO.setConsultId(consultSheetObj.getConsultId());
            consultSheetVO.setUserName(consultSheetObj.getUserName());
            consultSheetVO.setSex(consultSheetObj.getSex() == 1 ? "男" : "女");
            consultSheetVO.setPhone(consultSheetObj.getPhone());
            consultSheetVO.setPastRecords("0".equals(consultSheetObj.getPastRecords()) ? "否" : "是");
            consultSheetVO.setIllness("0".equals(consultSheetObj.getIllness()) ? "否" : "是");
            consultSheetVO.setAllergy("0".equals(consultSheetObj.getAllergy()) ? "否" : "是");
            consultSheetVO.setStatus("0".equals(consultSheetObj.getStatus()) ? "未审核" : "1".equals(consultSheetObj.getStatus()) ? "已通过" : "已拒绝");
            consultSheetVO.setPharmaName(consultSheetObj.getPharmaName());
            consultSheetVO.setCustomerName(consultSheetObj.getCustomerName());
            consultSheetVO.setDescription(consultSheetObj.getDescription());
            consultSheetVO.setCreateTime(DateUtils.formatDateTime(consultSheetObj.getCreateTime()));
            consultSheetVO.setAuditTime(consultSheetObj.getAuditTime() == null? "" : consultSheetObj.getAuditTime());
            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);
    }

    /**
     * 咨询单审核拒绝功能
     * @param consultId
     * @param status
     * @param description
     * @param request
     * @return
     */
    @RequestMapping(value = "/updateData")
    @ResponseBody
    public JSONObject updateData(Long consultId, String status, String description ,HttpServletRequest request) {
        JSONObject rtnJson = new JSONObject();
        ConsultSheet consultSheet = consultSheetService.fetchById(consultId);
        consultSheet.setDescription(description);
        try {
            if (consultId != null && StringUtils.isNoneBlank(status) && StringUtils.isNoneBlank(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日")};

                    String url = SystemConfig.p.getProperty("MOBILE_MP_DOMAIN_NAME") + "/addzxd?appid=" + appid + "&tokenId=1&consultId="+consultSheet.getId();
                    sendMessage(refuseTmpId, token, consultSheet.getOpenId(),first, remark, keywords, url);
                    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日")};
            String url = SystemConfig.p.getProperty("MOBILE_MP_DOMAIN_NAME") + "/addzxd?appid=" + appid + "&tokenId=1&consultId="+consultSheet.getId();
            sendMessage(refuseTmpId, token, consultSheet.getOpenId(),first, remark, keywords, url);

            e.printStackTrace();
            rtnJson.put("errorNo", 1);
        }
        return rtnJson;
    }

    /**
     * 咨询单审核通过
     * @param consultId
     * @param status
     * @param request
     * @return
     */
    @RequiresPermissions(value = CONSULTSHEET_EDIT)
    @RequestMapping("/updateStatus")
    @ResponseBody
    public JSONObject updateStatus(Long consultId, String status, Long pastRecords, Long allergy, String goodsDes, HttpServletRequest request) {
        Long accountId = UserUtils.getmpaccounts(request);
        JSONObject rtnJson = new JSONObject();
        ConsultSheet consultSheet = consultSheetService.fetchById(consultId);
        try {
            if (consultId != null && StringUtils.isNoneBlank(status)) {
                String contents =  ESAPI.encoder().decodeForHTML(goodsDes);
                goodsDes = HtmlUtils.htmlUnescape(contents);
                Integer integer = consultSheetService.updateStatus(consultId, status, goodsDes);
                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());
                    order.setAccountsId(accountId);
                    order.setStatus("0");//添加订单待确认
                    order.setDescription(goodsDes);

                    if (StringUtils.isNoneBlank(consultSheet.getAddressId())) {
                        Conds adsConds = new Conds();
                        adsConds.equal("t.del_flag", Constants.DEL_FLAG_0);
                        adsConds.equal("t.id", consultSheet.getAddressId());
                        Address address = addressService.fetchSearchByConds(adsConds);
                        if (address != null) {
                            order.setAddressId(address.getId());
                            order.setAddressDes(address.getProvinceName()+address.getCityName()+address.getCountyName()+address.getAddressName());
                        }
                    }

                    orderService.save(order);

                    //反写咨询单
                    if (pastRecords != null) {
                        consultSheet.setPastRecords(pastRecords);
                    }
                    if (allergy != null) {
                        consultSheet.setAllergy(allergy);
                    }
                    consultSheet.setStatus(status);
                    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 url = SystemConfig.p.getProperty("MOBILE_MP_DOMAIN_NAME") + "/zxdxq?appid=" + appid + "&tokenId=1&id="+consultSheet.getId();
                    String [] keywords = {consultSheet.getUserName(),
                            order.getNumber()};
                    sendMessage(refuseTmpId, token, consultSheet.getOpenId(),first, remark, keywords, url);

                    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日")};
            String url = SystemConfig.p.getProperty("MOBILE_MP_DOMAIN_NAME") + "/addzxd?appid=" + appid + "&tokenId=1&consultId="+consultSheet.getId();
            sendMessage(refuseTmpId, token, consultSheet.getOpenId(), first, remark, keywords, url);

            e.printStackTrace();
            rtnJson.put("errorNo", 1);
        }
        return rtnJson;
    }

    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);
    }
}
